在C++中可以做到這一點嗎?繼承:從基類調用派生類函數
class Base {
int a(Derived d) { d.b(); }
};
class Derived : public Base {
int b();
};
我應該在Base.hpp中包含Derived.hpp嗎?
在C++中可以做到這一點嗎?繼承:從基類調用派生類函數
class Base {
int a(Derived d) { d.b(); }
};
class Derived : public Base {
int b();
};
我應該在Base.hpp中包含Derived.hpp嗎?
在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();
};
下編譯:
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(); }
它編譯,是的。雖然我擔心這不是問題(正如你在評論中提到的那樣)。 –
這是可能的調用函數從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;
}
};
這是另一種方法,是的。 –
在'Base'中創建'b()'純虛函數。 –
歡迎使用堆棧溢出。請花些時間閱讀[The Tour](http://stackoverflow.com/tour),並參閱[幫助中心](http://stackoverflow.com/help/asking)中的資料,瞭解您可以在這裏問。 –
使用前向聲明和定義中的分割聲明,您的示例可能有效。但我不確定你展示的是什麼你真正想要的。 – Jarod42