gpt4 book ai didi

C++:重载 I/O 运算符

转载 作者:行者123 更新时间:2023-11-28 02:28:05 25 4
gpt4 key购买 nike

我是 C++ 的新手,我似乎无法弄清楚重载 I/O 运算符。我已阅读:

但不幸的是,我无法做到正确。我到目前为止的代码如下:

#include <iostream>
#include <string>

// Sales_data structure
struct Sales_data {
std:: string bookNo;
unsigned units_sold = 0;
double revenue = 0.0;
};

// logic to determine if sales data are not equal
bool operator!=(const Sales_data& data1, const Sales_data& data2) {
// boolen comparision to produce not equal
return data1.bookNo != data2.bookNo;
}

ostream& operator<< (ostream &out, Sales_data &cSales_data) {
out << "(" << cSales_data.bookNo << " " << cSales_data.units_sold
<< " " << cSales_data.revenue << ")";
return out;
}

int main() {
Sales_data books; // books is of type sales_data uninitialized
double price = 0; // price is of int type initialized at 0
for (int i = 0; i >= 0; ++i) {
while (std::cin >> books.bookNo >> books.units_sold >> price) {
if (books != Sales_data()) {
i += 1;
// there is other code here but not relevant to the problem.
std::cout << books << std::endl;
}
}
}
return 0;
}

我得到的错误是

 error: ‘ostream’ does not name a type
ostream& operator<< (ostream &out, Sales_data &cSales_data) {
^
exercise2_41a.cpp: In function ‘int main()’:
exercise2_41a.cpp:52:22: error: cannot bind ‘std::ostream {aka
std::basic_ostream<char>}’ lvalue to ‘std::basic_ostream<char>&&’
std::cout << books << std::endl;

我遇到问题的代码是

ostream& operator<< (ostream &out, Sales_data &cSales_data) {
out << "(" << cSales_data.bookNo << " " << cSales_data.units_sold
<< " " << cSales_data.revenue << ")";
return out;
}

但我不太确定我需要做什么才能达到预期的结果。我错过了什么?我相信我走在正确的轨道上,但这也可能是一场闹剧。

最佳答案

std::ostream& operator<< (std::ostream &out, const Sales_data &cSales_data)

关于C++:重载 I/O 运算符,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29860295/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com