纯虚拟类中的运算符重载

时间:2014-06-29 18:41:59

标签: c++ operator-overloading pure-virtual

您好我要为原始类型创建类似包装类的东西,但我坚持这个问题:

当我尝试创建界面并能够将多态性与后代一起使用时

修改

我正在

function returning abstract class "Var" is not allowed: 
function "Var::operator+" is a pure virtual 
function function "Var::operator-" is a pure virtual function 
function "Var::operator*" is a pure virtual function 
function "Var::operator/" is a pure virtual function

这是我的代码

class Var
{

public:
    Var() {  }
    virtual Var operator+(Var b) = 0;
    virtual Var operator-(Var b) = 0;
    virtual Var operator*(Var b) = 0;
    virtual Var operator/(Var b) = 0;
};

class Decimal : public Var
{

public:
    Decimal(double a) { value = a; }
    Decimal() : Decimal(0) {  };
    virtual Decimal operator+( Decimal b)
    {
        return value + b.value;
    }
    virtual Decimal operator-( Decimal b)
    {
        return value - b.value;
    }
    virtual Decimal operator*( Decimal b)
    {
        return value * b.value;
    }
    virtual Decimal operator/( Decimal b)
    {
        return value / b.value;
    }
    Decimal operator=(double val)
    {
        value = val;
    }

private:
    double value;
};

我的问题的任何解决方案?

1 个答案:

答案 0 :(得分:1)

我认为你这是错误的做法。试试模板

template<class T>
class Var
{
public:
    typedef T Type;

    Var(const Type& value = Type()) : value(value) {}

    friend Var operator+(const Var& left, const Var& right)
    {
        return Var(left.value + right.value);
    }

private:
    Type value;
};