c – 抽象类的逆变

我想在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

相关文章

本程序的编译和运行环境如下(如果有运行方面的问题欢迎在评...
水了一学期的院选修,万万没想到期末考试还有比较硬核的编程...
补充一下,先前文章末尾给出的下载链接的完整代码含有部分C&...
思路如标题所说采用模N取余法,难点是这个除法过程如何实现。...
本篇博客有更新!!!更新后效果图如下: 文章末尾的完整代码...
刚开始学习模块化程序设计时,估计大家都被形参和实参搞迷糊...