我有这个类的定义:如果C++中+运算符重载的第二个操作数为零,如何返回第一个操作数?
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 ='。 – 0x499602D2
如果第二个操作数丢失,你的代码看起来像'c = a +;',对吧?这根本不会编译。 –
你能更具体吗?用代码示例? @ 0x499602D2 – MinimalTech