重载流插入和提取操作符

Overload stream insertion and extraction operator

我正在尝试为我的 Entrepreneur class.

重载流插入和提取运算符

我的企业家 class:

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;
}

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

Binary Operator '>>' can't be applied to the expression of type 'istream' and 'Entrepreneur'

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

签名有误。您正在使用 friend,因为您想要 declare/define 非成员函数。放下Enterpreneur::,问题就解决了。

class' 的定义应该类似于:

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 关键字),或将它们定义为内联 class.