我有问题,运算符重载:
我想写与运营商的一类这样的:C++暧昧的操作模板超载
class BigNum
{
public:
template<class T>
bool operator==(const T &input);
template<class T>
friend bool operator==(const T &A,BigNum & B);
};
它的优良拨打:
BigNum A;
int a;
A==a;
a==A;
但是,当打电话:
BigNum A,B;
A==B;
它会得到编译器错误:
[Error] ambiguous overload for 'operator==' (operand types are 'BigNum' and 'BigNum')
[Note] bool BigNum::operator==(const T&) [with T = BigNum]
[Note] bool operator==(const T&, BigNum&) [with T = BigNum]
而且还有如果我改变同样的问题
template<class T>
bool operator==(const T &input);
到
bool operator==(const BigNum &input);
但如果操作符重载都是这样(但它不能做Any type==BigNum
)就OK :
class BigNum
{
public:
bool operator==(const BigNum &input);
template<class T>
bool operator==(const T &input);
};
如果我要写入运算符重载,以便它可以做所有这些:
- 任何类型的== BIGNUM
- BIGNUM ==任何类型
- BIGNUM == BIGNUM
我应该如何修复它?谢谢。
您需要三个重载 - 一个取两个'BigNum'的非模板,另一个取两个'BigNum',另一个取''T'(左边的'BigNum'可以是member功能,但个人而言,我会让所有三个非成员,对称)。 –
当你说“可以打电话:...但是当打电话:...错误...”你的代码有一个赋值运算符'='不等价'==' – doctorlove