假设我有两个类:
class A
{
public:
A* Hello()
{
return this;
}
}
class B:public class A
{
public:
B* World()
{
return this;
}
}
假设我有一个 B
类的实例,如下所示:
B test;
如果我调用 test.World()->Hello()
就可以了。
但是 test.Hello()->World()
将无法工作,因为 Hello()
返回 A
类型。
如何让 Hello()
返回 B
的类型?我不想使用 virtual
函数,因为我们有 20 多个不同的类继承 A
。
最佳答案
您可以使用 CRTP ,奇怪的重复模板模式:
template<class Derived>
class A {
public:
Derived* Hello() {
return static_cast<Derived*>(this);
}
};
class B : public A<B> {
public:
B* World() {
return this;
}
};
int main() {
B test;
test.World()->Hello();
test.Hello()->World();
}
关于c++ - 继承 : Function that returns self type?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11761506/