运算符重载时遇到的问题:没有找到可接受类型的左运算符(Visual Studio 报错 C2678 )
*在学习运算符重载时,在书写下列代码时,遇到问题:没有找到接受类型的左操作数运算符(或没有可接受的转换)
VS2019报错如下
#include<iostream>
#include<string>
#include<math.h>
using namespace std;
class T {
public:
T(int n, int n2) :m(n), n(n2) {};
friend T operator-(T& ,T& );
friend T operator+(T &,T&);
T operator/(T);
int a = 10;
private:
int m, n;
};
T operator-(T &a,T &b)
{
int x1, x2;
x1 = a.m - b.m;
x2 = a.n - b.n;
T C(x1, x2);
return C;
}
T operator+(T &a,T &b)
{
int x1, x2;
x1 = a.m + b.m;
x2 = a.n + b.n;
T C(x1, x2);
return C;
}
T T::operator/(T A)
{
int c=m / A.m;
return T(c, 1);
}
int main()
{
T A(2, 4), B(8, 20), C(0, 0);
C = A + B-A;
C = A / B;
}
后来在舍友的帮助下,我们成功得出我C语言没学好的结论,修改代码如下
class T {
public:
T(int n, int n2) :m(n), n(n2) {};
friend T operator-(const T& ,const T& );
friend T operator+(const T &,const T&);
T operator/(T);
int a = 10;
private:
int m, n;
};
T operator-(const T &a,const T &b)
{
int x1, x2;
x1 = a.m - b.m;
x2 = a.n - b.n;
T C(x1, x2);
return C;
}
T operator+(const T &a,const T &b)
{
int x1, x2;
x1 = a.m + b.m;
x2 = a.n + b.n;
T C(x1, x2);
return C;
}
原来是在计算:C=A+B-A 时,按照顺序从左到右,先计算A+B,运算符重载函数返回为一个临时对象,把一个临时对象作为函数参数,重载运算符“-”时,出现问题。因为临时对象的值不能修改,所以加const修饰符后,就ok了。