[英]Overloading = operator
I wrote the following test program:我编写了以下测试程序:
int main(int argc, char** argv)
{
ifstream inFile;
inFile.open("D:\\C++\\Assignments\\in1.txt");
if (!inFile) {
cout << "Unable to open file";
exit(1); // terminate with error
}
Complex a,b,c;
inFile >> a;
inFile >> b;
ofstream out;
out.open("D:\\C++\\Assignments\\out1.txt");
out << a <<endl<< b<<endl; // dumps data to a stream connected to a file
out << c=a <<endl;
out.close();
return 0;
}
I have overloaded = as following:我已经重载 = 如下:
void Complex::operator=(const Complex &a)//mulptiplication
{
real=a.real;
imag=a.imag;
}
But I am getting errors like: no match for ooperator <<.但是我收到了类似的错误:与操作符<<不匹配。 Can anyone help with the error?
任何人都可以帮助解决错误吗?
This is your problem:这是你的问题:
out << c=a <<endl;
You need to return a Complex&您需要返回一个 Complex&
Try this:尝试这个:
Complex& Complex::operator=(const Complex &a)//mulptiplication
{
real=a.real;
imag=a.imag;
return *this;
}
The reason is that c=a yields a void and there is no operator<< that works for void on the left hand side原因是 c=a 产生一个 void 并且没有操作符<<适用于左侧的 void
Just for clarity, you might rewrite as:为了清楚起见,您可以重写为:
c = a;
out << c << endl;
ortang is also right that there must be an operator<< for the Complex class. ortang 也是对的,Complex 类必须有一个 operator<<。
The problem lies in out << a << endl << b << endl
, since you did not overload the operator<<
for the Complex
class i guess.问题在于
out << a << endl << b << endl
,因为我猜您没有为Complex
类重载operator<<
。
Take a look at this SO post how to overload the operator<<
.看看这个 SO post如何重载
operator<<
。
If real
and imag
are themselves of types with correct assign semantics (for example primitive types like int
or double
), then it is redundant and error-prone to implement your own operator=
.如果
real
和imag
本身是具有正确赋值语义的类型(例如像int
或double
这样的原始类型),那么实现自己的operator=
是多余且容易出错的。 Just use the compiler-generated one.只需使用编译器生成的一个。
Even with proper operators即使有适当的操作员
out << c=a <<endl;
which is parsed as被解析为
(out << c) = (a <<endl);
the error occurs, due to operator precedence.由于运算符优先级,会发生错误。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.