C ++二进制表达式的无效操作数('IOperand *'和'IOperand *')

时间:2017-07-22 20:18:52

标签: c++ c++11 operator-overloading overloading

我知道问题已被多次询问,但我无法找到问题的答案,

我有这个运算符重载:

virtual IOperand *operator+(const IOperand &rhs) const = 0; //sum

来自这个界面:

class IOperand
{
  public:
    virtual std::string toString() const = 0; //stringthatrepresentstheinstance

    virtual eOperandType getType() const = 0; //returnsthetypeofinstance

    virtual IOperand *operator+(const IOperand &rhs) const = 0; //sum
    virtual IOperand *operator-(const IOperand &rhs) const = 0; //difference
    virtual IOperand *operator*(const IOperand &rhs) const = 0; //product
    virtual IOperand *operator/(const IOperand &rhs) const = 0; //quotient
    virtual IOperand *operator%(const IOperand &rhs) const = 0; //modulo

    virtual ~IOperand() {}
};

此接口由6个类“Int8”,“Int16”,“Int32”,“Float”,“Double”,“BigDecimal”继承并覆盖:

class Int8 : public IOperand
{
  private:
    std::string valueUnmodified;
    int8_t value;

  public:
    Int8(std::string my_value);
    virtual ~Int8();
    virtual std::string toString() const;
    virtual eOperandType getType() const;
    virtual IOperand *operator+(const IOperand &rhs) const;
    virtual IOperand *operator-(const IOperand &rhs) const;
    virtual IOperand *operator*(const IOperand &rhs) const;
    virtual IOperand *operator/(const IOperand &rhs) const;
    virtual IOperand *operator%(const IOperand &rhs) const;
};

以下是如何在Int8类中编写此运算符+

IOperand *Int8::operator+(const IOperand &rhs) const
{
    if (rhs.getType() != eOperandType::INT8)
        throw avm::AvmError("Operator error");
    int8_t nb;
    nb = std::stoi(rhs.toString());
    int8_t result;
    result = this->value + nb;

    return new Int8(std::to_string(result));
}

对我来说,直到这里看起来还不错,但当我尝试使用运算符+时:

IOperand *first = stack_.top();
IOperand *second = stack_.top();

IOperand *result = first + second;

我有错误:

invalid operands to binary expression ('IOperand *' and 'IOperand *')

IOperand *result = first + second;

我很难弄清楚发生了什么,请帮助

ps:stack_是一个std :: stack,是的,它不是空的

1 个答案:

答案 0 :(得分:0)

operator +需要根据原型

引用
   virtual IOperand *operator+(const IOperand &rhs) const;

但是你尝试添加指针:

IOperand *first = stack_.top();
IOperand *second = stack_.top();

IOperand *result = first + second;

// should be 
IOperand *result = *first + *second;