加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

c – 继承:返回自身类型的函数?

发布时间:2020-12-16 03:05:22 所属栏目:百科 来源:网络整理
导读:假设我有两个课程: 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()不
假设我有两个课程:
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()返回一个类型.

我如何使Hello()返回B的类型?我不想使用虚拟函数,因为我们有超过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();
}

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读