【发布时间】:2014-04-24 05:57:53
【问题描述】:
在 C++ 上是否可以两次重载同一个运算符?
当我尝试使用返回类型作为基础重载 + 运算符时,编译器会显示一个错误。
bigint.h:41:9: error: ‘std::string BigInt::operator+(BigInt)’ cannot be overloaded
bigint.h:40:9: error: with ‘BigInt BigInt::operator+(BigInt)’
这是我的代码:
.h:
BigInt operator + (BigInt);
string operator + (BigInt);
.cc:
BigInt BigInt::operator + (BigInt M){
if (this->number.size() != M.number.size())
fixLength (this->number, M.number);
// Call Sum;
this->number = Sum (this->number, M.number);
return (*this);
}
string BigInt::operator + (Bigint M){
// Call BigInt overload +;
}
编辑:显然我不能使用返回类型作为基础重载同一个运算符两次。有什么建议吗?
【问题讨论】:
-
不,这是不可能的。编译器不知道你想要哪个版本,它会从参数中扣除。
-
你可以重载多次,但不能通过返回类型。
标签: c++