2016-12-26 121 views
0

在C++中可以做到這一點嗎?繼承:從基類調用派生類函數

class Base { 
    int a(Derived d) { d.b(); } 
}; 

class Derived : public Base { 
    int b(); 
}; 

我應該在Base.hpp中包含Derived.hpp嗎?

+0

在'Base'中創建'b()'純虛函數。 –

+0

歡迎使用堆棧溢出。請花些時間閱讀[The Tour](http://stackoverflow.com/tour),並參閱[幫助中心](http://stackoverflow.com/help/asking)中的資料,瞭解您可以在這裏問。 –

+0

使用前向聲明和定義中的分割聲明,您的示例可能有效。但我不確定你展示的是什麼你真正想要的。 – Jarod42

回答

1

在C++中可以做到這一點嗎?

是的,這是在C++語言的使用非常簡單,基本的模式(稱爲多態性或Template Method Pattern):

class Base { 
    int a() { b(); } // Note there's no parameter needed! 
// Just provide a pure virtual function declaration in the base class 
protected:  
    virtual int b() = 0; 

}; 

class Derived : public Base { 
    int b(); 
}; 
+0

您必須記住不要在構造函數或析構函數中調用這些函數,否則您將以純函數調用結束。 – paweldac

+0

@paweldac幸運的是,在OP的示例中並非如此。如果需要這樣做,你的答案可以解決這個問題。 –

+0

只是想向其他可能使用提議代碼的讀者說清楚。沒錯,在OP的問題中,這個錯誤不會出現:) – paweldac

0

下編譯:

class Derived; 

class Base { 
public: 
    int a(Derived d); 
}; 

class Derived : public Base { 
public: 
    int b() { return 42; } 
}; 

int Base::a(Derived d) { d.b(); } 
+0

它編譯,是的。雖然我擔心這不是問題(正如你在評論中提到的那樣)。 –

0

這是可能的調用函數從C++習慣用語的基類派生類調用:「好奇地重現模板模式」CRTP。請在下面找到以下呼叫:

template <class Child> 
struct Base 
{ 
    void foo() 
    { 
     static_cast<Child*>(this)->bar(); 
    } 
}; 

struct Derived : public Base<Derived> 
{ 
    void bar() 
    { 
     std::cout << "Bar" << std::endl; 
    } 
}; 
+0

這是另一種方法,是的。 –