这段代码可以帮助理解我想要什么:
class Base
{
public:
void foo()
{
print("Base\n");
Derived::foo(); // smth like that.
}
};
class Derived:public Base
{
public:
void foo()
{
print("Derived\n");
}
}
int main()
{
Derived bar;
bar.foo();
return 0;
}
有什么想法吗?
附言非常糟糕的想法是传递给派生的 foo 指针。
最佳答案
您需要基类来保存它的派生类的句柄,如下例所示:
template<typename T>
class Base {
T *handle;
protected:
Base(T *_handle) : handle(_handle) {}
public:
void foo() {
std::cout << "Base" << std::endl;
handle->foo();
}
};
class Derived : public Base<Derived> {
public:
Derived() : Base(this) { }
void foo() { std::cout << "Derived" << std::endl; }
};
关于C++ 如何首先从基类调用相同的方法,然后从派生类调用?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25067138/