我在课程中重载了运算符,这就是我所做的:
首先,vver加载'<<'运算符以将类的对象插入到ostream [Success]
class complex
{
friend ostream & operator<<(ostream &os, const complex &z);
// codes that worked!
}
ostream& operator<<(ostream &os, const complex &z) {// conditions}
然后,我想做类似于'>>'的运算符,允许使用'>>'从istream中提取类的对象。所以我按照MSDN的文档:
// Inside the class declaration:
friend istream& operator>>(istream &is, const complex &z);
// Outside the class, before main function:
istream& operator>>(istream &is, const complex &z)
{
is >> z.re >> z.im; // 're' and 'im' corresponds to real or imaginary numbers which are stored as doubles in each complex object
return is;
}
虽然它具有与MSDN中的示例代码相同的格式,但这导致编译错误:
error: invalid operands to binary expression ('istream'
(aka 'basic_istream<char>') and 'double')
is >> z.re >> z.im;
有人可以帮我理解错误信息,或者如果你能告诉我的代码中的错误,可以指出我做错了什么。干杯。
正如@BoPersson和@molbdnilo在注释中指出的那样,输入操作符应该使用非const引用来更新参数。要更新对象,我们需要在类的公共成员下添加两个void函数:
// The following codes are to be added inside the class
// Function to set the real part of a complex object
void setReal(double realPart){
re = realPart;
}
// Function to set the imaginary part of a complex object
void setImg(double imaginaryPart){
im = imaginaryPart;
}
将“朋友”放入类中后,重载函数在类外声明:
istream& operator>>(istream &is, complex &z)
{
// Declare variables
double realPart, imaginaryPart;
// Extract real and imaginary parts from istream and save to above variables
is >> realPart >> imaginaryPart;
// Assign values to real and imaginary parts of a complex number in istream
z.setReal(realPart);
z.setImg(imaginaryPart);
return is;
}
现在我们可以从main中的istream中提取复杂(类)对象:
complex cNum;
cout << "Enter real and imaginary parts of a complex number: " << endl;
cin >> cNum;
然后,重载的运算符“<<”可用于打印出所选的复数。