在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