【问题标题】:Using non-member function to extract class-objects from an input stream使用非成员函数从输入流中提取类对象
【发布时间】:2018-03-05 14:32:34
【问题描述】:

我尝试了使用类的重载运算符,这就是我所做的:

首先,vverloading '

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;

谁能帮我理解错误信息,或者如果你能说出我的代码中的错误,请指出我做错了什么。干杯。

【问题讨论】:

  • 输入运算符必须使用非常量引用才能更新参数。
  • 我很确定 MSDN 在第二个参数上没有 const
  • 谢谢!我已经解决了这个问题并编写了一个全面的解决方案来重载“>>”运算符。

标签: c++ class operator-overloading


【解决方案1】:

正如@BoPersson 和@molbdnilo 在cmets 中指出的那样,输入运算符应该使用非常量引用来更新参数。要更新对象,我们需要在类的公共成员下添加两个 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;
}

现在我们可以主要从 istream 中提取复杂(类)对象:

complex cNum;
cout << "Enter real and imaginary parts of a complex number: " << endl;
cin >> cNum;

然后可以使用重载的运算符“

【讨论】:

    猜你喜欢
    • 2012-01-02
    • 1970-01-01
    • 2014-02-04
    • 2015-04-29
    • 1970-01-01
    • 2013-07-18
    • 2015-08-08
    相关资源
    最近更新 更多