在C ++中可以做到这一点吗?
class Base {
int a(Derived d) { d.b(); }
};
class Derived : public Base {
int b();
};
我是否应该在Base.hpp中包含Derived.hpp?
答案 0 :(得分: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();
};
答案 1 :(得分: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(); }
答案 2 :(得分:0)
可以使用C ++惯用法从Base类调用Derived类中的函数:"好奇地重现模板模式" 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;
}
};