使用非成员函数从输入流中提取类对象

时间:2018-03-05 14:32:35

标签: c++ class operator-overloading

我参加了重载操作员的课程,这就是我所做的:

首先,vverloading'<<<<<运算符将类的对象插入ostream [成功]

class complex
{
    friend ostream & operator<<(ostream &os, const complex &z);

    // codes that worked!
}

ostream& operator<<(ostream &os, const complex &z) {// conditions}

然后,我想做与'&gt;&gt;'相似的事情。运营商,允许使用'&gt;&gt;'从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;

有人可以帮助我理解错误信息,或者如果你能告诉我的代码中的错误,可以指出我做错了什么。欢呼声。

1 个答案:

答案 0 :(得分:1)

正如@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;
}

放了一个朋友&#39;在类中,重载函数在类外声明:

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;

重载运营商&#39;&lt;&lt;&#然后可以用来打印出选定的复数。