继承:返回自我类型的函数? [英] Inheritance: Function that returns self type?

查看:104
本文介绍了继承:返回自我类型的函数?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设我有两个类:

class A
{
    public:
    A* Hello()
    {
        return this;
    }
}

class B:public class A
{
    public:
    B* World()
    {
        return this;
    }
}

假设我有一个 B 这样的类:

And let's say I have an instance of B class like so:

B test;

如果我调用 test.World() - > Hello / code>这将工作正常。
但是测试.Hello() - > World() A 类型。

如何使 >返回 B 的类型?我不想使用 virtual 函数,因为我们有超过20个不同的类继承 A

How could I make Hello() return the type of B? I don't want to use a virtual function since we have over 20 different classes inheriting 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();
}

这篇关于继承:返回自我类型的函数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆