此代码有助于理解我想要的内容:
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;
}
有什么想法吗?
P.S。非常糟糕的主意是传递给派生的foo指针。
答案 0 :(得分:5)
您需要基类来保留它的派生类的句柄,如下例所示:
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; }
};
答案 1 :(得分:2)
改编自here:
class Derived:public Base
{
public:
void foo()
{
Base::foo();
print("Derived\n");
}
}
int main()
{
Derived bar;
bar.foo();
}
似乎就是你想要的。
答案 2 :(得分:2)
你可以在Base中声明一个子类必须覆盖的抽象方法,但是你可以调用它,尽管它是抽象的。这称为模板方法:
class Base
{
public:
void foo() {
print("Base\n");
_foo();
}
private:
virtual void _foo() = 0;
};
class Derived: public Base
{
virtual void _foo() {
print("Derived\n");
};
};
另一种选择是使Base成为模板并传递Derived类型:
template<class D>
class Base
{
public:
void foo() {
print("Base\n");
D::foo();
}
};
class Derived: public Base<Derived>
{
public:
void foo() {
print("Derived\n");
};
};
我通常会采用第一种方法,因为它更容易掌握,并且可以使用多个级别的继承。
答案 3 :(得分:1)
像
这样的东西class Derived : public Base
{
public:
void foo()
{
Base::foo();
printf("Derived\n");
}
};
然后
int main()
{
Derived bar;
bar.foo();
return 0;
}
或强>
int main()
{
Derived bar;
bar.Base::foo();
bar.Derived::foo();
return 0;
}
答案 4 :(得分:0)
您正在描述静态多态,由CRTP解决:
template <typename DERIVED>
class Base
{
public:
DERIVED & derived() { return *static_cast<DERIVED *>(this); }
void foo()
{
print("Base\n");
derived().foo();
}
};
class Derived:public Base<Derived>
{
public:
void foo()
{
print("Derived\n");
}
};
答案 5 :(得分:0)
您需要一个虚拟功能。
#include "windows.h"
#include <iostream>
class Base
{
public:
virtual void foo() const
{
std::cout << "Base\n";
}
};
class Derived : public Base
{
public:
void foo() const
{
Base::foo();
std::cout << "Derived\n";
}
};
void main()
{
Derived d; // call Base::foo on this object
d.foo();
system("pause");
}