过载流插入和提取操作符

时间:2016-04-06 20:24:53

标签: c++ class operator-overloading friend

我正在尝试为我的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;
}

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

  

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

你能帮我解一下上面代码的错误吗?

1 个答案:

答案 0 :(得分: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关键字),或者将它们与类内联定义。