【问题标题】:C++ invalid operands to binary expression ('IOperand *' and 'IOperand *')二进制表达式的 C++ 无效操作数('IOperand *' 和 'IOperand *')
【发布时间】:2017-07-22 20:18:51
【问题描述】:

我知道这个问题已被问过很多次,但我找不到我的问题的答案,

我有这个运算符重载:

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 类中这个 operator+ 的写法

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));
}

对我来说,直到这里看起来还不错,但是当我尝试像这样使用 operator+ 时:

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 是的,它不是空的

【问题讨论】:

  • 您不能为任何类型的指针重载运算符。
  • 而且添加两个指针没有意义。
  • 即使像这样取消引用它: IOperand *result = first + (*second);我得到二进制表达式的无效操作数('IOperand *' 和 'IOperand')
  • first 仍然是一个指针,而不是一个 IOperand。您在这里尝试做的只是被误导了。
  • 谢谢你,尼尔,我明白我的错误了。

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


【解决方案1】:

运营商 + 根据您的原型需要参考

   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;

【讨论】:

    猜你喜欢
    • 2016-02-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-08-20
    • 2012-04-16
    • 1970-01-01
    相关资源
    最近更新 更多