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

c – 抽象类的逆变

发布时间:2020-12-16 05:43:17 所属栏目:百科 来源:网络整理
导读:我想在C上创建一个很好的接口,每个实现都需要在其上定义添加. 我想做这样的事情: class A{ ... virtual A operator+(const A other) =0; ... } // this is my interface or abstract class. class B : A{ ... B operator+(const B other); ... } // this is
我想在C上创建一个很好的接口,每个实现都需要在其上定义添加.

我想做这样的事情:

class A{
        ...
        virtual A& operator+(const A& other) =0;
        ...
    }
    // this is my interface or abstract class.


    class B : A{
        ...
        B& operator+(const B& other);
        ...
    }
    // this is the kind of implementation i would like. a B element can be added by another B element only ! At least this the constraint I am aiming at.

因为c不接受逆变,我的功能B&运算符(const B& other)不实现虚拟A&运算符(const A& other).有没有什么棘手的(但有点干净……)方法呢?

解决方法

template<class Y>
class A
{
    virtual Y& operator+=(const Y& other) = 0;
};

class B : A<B>
{
    // must implement B& operator+=(const B& other) else B is abstract
};

是一种方式.这个习惯用法在实施政策时很常见.见http://en.wikipedia.org/wiki/Curiously_recurring_template_pattern

(编辑:李大同)

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

    推荐文章
      热点阅读