我对运算符重载有疑问:
我想用这样的运算符编写一个类:
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
):
class BigNum
{
public:
bool operator==(const BigNum &input);
template<class T>
bool operator==(const T &input);
};
如果我想编写运算符重载以便它可以完成所有这些操作:
- 任何类型 == BigNum
- BigNum == 任何类型
- BigNum == BigNum
我该如何解决?谢谢。
最佳答案
我建议删除一个成员 ==
模板,只为 operator==
提供三个非成员重载 - 两个模板化,一个带有 BigNum
在左侧,另一个在右侧;和一个非模板化的 BigNum
两边。
关于用于模板重载的 C++ 模糊运算符,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40531502/