【问题标题】:Overload stream insertion and extraction operator [closed]重载流插入和提取运算符 [关闭]
【发布时间】:2016-04-06 20:24:53
【问题描述】:

我正在尝试为我的Entrepreneur 类重载流插入和提取运算符。

我的企业家课程有以下内容:

friend istream& Entrepreneur::operator>> (istream &input, Entrepreneur &entrepreneur) {
    cout << "Please enter the item to be sold: ";
    input >> entrepreneur.Item;
    cout << "\nPlease enter the donation amount received: ";
    input >> entrepreneur.Donation;
    cout << "\nPlease enter the amount of members in the group: ";
    input >> entrepreneur.Nr;
    cout << "\nPlease enter the startup amount received: ";
    input >> entrepreneur.StartupAmt;
    cout << endl;
    return input;
}

friend ostream& Entrepreneur::operator<< (ostream &output, Entrepreneur &entrepreneur) {
    output << "Item: " << entrepreneur.Item << endl;
    output << "Members in group: " << entrepreneur.Nr << endl;
    output << "Startup amount: " << entrepreneur.StartupAmt << endl;
    output << "Donation amount: " << entrepreneur.Donation << endl;
    output << "Expenses: " << entrepreneur.Expenses << endl;
    output << "Points earned: " << entrepreneur.Points << endl;
    output << "All items sold: " << entrepreneur.Sold ? "Yes" : "No" << endl;
    return output;
}

在我的 main.cpp 文件中,我正在尝试以下代码:

int main() {
    Entrepreneur Group3;
    cin >> Group3;
}

代码无法编译。我收到以下错误消息:

二元运算符'>>'不能应用于'istream'和'Entrepreneur'类型的表达式

你们能帮我弄清楚上面的代码有什么问题吗?

【问题讨论】:

标签: c++ class operator-overloading friend


【解决方案1】:

签名错误。您正在使用朋友,因为您想声明/定义非成员函数。删除Enterpreneur::,问题就解决了。

类的定义应该类似于:

class Enterpreneur
{
public:
    ...

    friend istream& operator>> (istream &input, Entrepreneur &entrepreneur);
    friend ostream& operator<< (ostream &output, Entrepreneur const& entrepreneur);
    //                                                        ^^^^^
    //                                    we're not modifying the argument, are we?
};

然后将这些运算符定义为任何其他非成员函数(没有friend 关键字),或者将它们定义为与类内联。

【讨论】:

  • 感谢您的帮助。它现在可以编译,但我现在收到此错误消息:'friend' used outside of class
  • @Henry 查看编辑。
  • 感谢它现在正在工作!
猜你喜欢
  • 2012-09-19
  • 2012-08-10
  • 2012-05-10
  • 1970-01-01
  • 2017-09-11
  • 1970-01-01
  • 1970-01-01
  • 2021-04-24
  • 1970-01-01
相关资源
最近更新 更多