【发布时间】: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