【发布时间】:2014-01-29 18:19:03
【问题描述】:
我有这个类定义:
class foo{
public:
foo();
foo(const int& var);
foo(const foo& var);
~foo();
const foo operator +(const foo& secondOp) const;
private:
int a;
//plus other values, pointers, e.t.c.
};
我还为“+”运算符重载做了这个实现:
const foo foo::operator +(const foo& secondOp) const{
//I want here to check if i have one operand or two...
if ((FIRST_OPERAND.a!=0) && (secondOp.a==0)){
cout << "ERROR, second operand is zero";
return FIRST_OPERAND;
}
else if ((FIRST_OPERAND.a==0) && (secondOp.a!=0)){
cout << "ERROR, first operand is zero";
return secondOp;
}
}
当我写信给main():
foo a(2);
foo b;
foo c;
//I want here to print the ERROR and
//return only the values of a
c = a + b;
- 如果第二个操作数为零,我如何
return第一个操作数的值,反之亦然?
【问题讨论】:
-
让
operator+返回一个带有相关信息的任意类型的对象,并仅为该类型重载operator=。 -
如果缺少第二个操作数,您的代码将类似于
c = a + ;,对吧?那根本无法编译。 -
你能说得更具体点吗?有一个代码示例? @0x499602D2
-
operator+()的第二个操作数永远不会丢失。它从不参与表达式c = a;。在这种情况下,将使用默认生成的分配。 -
@OliCharlesworth 抱歉,我不是那个意思!!让我纠正一下……
标签: c++ operators operator-overloading