c++ - 继承 : Function that returns self type?

标签 c++

假设我有两个类:

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/

相关文章:

C++ - 如何使用 Curlpp 或 libcurl 发送 HTTP post 请求

c++ - C++中内置类型的自定义构造函数

c++ - 编译时专门针对函数指针引用以避免 -Waddress

c++ - 最佳 PCL 模板对齐设置

c++ - 将配置从 Debug 更改为 Release 时出现链接错误

c++ - 通过可变参数模板进行通用聚合初始化

c++ - 解决由于类之间的循环依赖导致的构建错误

c++ - Boost::log 静态工厂方法

c++ - 为什么地址零用于空指针?

c++ - string 和 const char*,哪个作为构造函数参数效率更高