C++:重载 I/O 运算符
C++: overloading the I/O operators
我是C++新手,我似乎无法弄清楚 I/O 运算符的过载。我读过:
- 重载运算符<<:无法将左值绑定到"std::basic_ostream
&&" - 重载运算符<<:无法将"std::basic_ostream
"左值绑定到"std::basic_ostream &&" - std::ostream {aka std::basic_ostream
} Ivalue to 'std::basic_ostream && - 在学习 cpp 上重载 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)
将
函数中所有ostream
实例替换为 std::ostream
。 它们是不同的,后者是您需要的。
(可选)使operator<<()
的第二个参数接受const
引用。
相关文章:
- 使用C++中的模板和运算符重载执行矩阵运算
- 为什么这个运算符<重载函数对 STL 算法不可见?
- <T> 通过模板化运算符重载将 std::complex 乘以双倍
- C++20概念:需要运算符重载
- 使用赋值运算符重载从类中返回jobject
- 在运算符重载定义中使用成员函数(const错误)
- 字节到位运算符重载C++
- 为什么在运算符重载时需要参考?
- 类中 c++ 的运算符 + 重载
- 算术复合运算符重载为非成员
- 运算符重载 (+),用于添加两个具有 C++ 的数组
- 交换运算符 + 重载会导致无限递归
- 如何理解新的运算符重载?
- 向量保持复数的运算符重载
- 如何创建运算符重载?
- 链接列表运算符重载没有打印出我想要的内容
- C++:需要帮助了解运算符重载错误
- 使用模板化运算符重载 XOR 运算符失败
- 如何确保接受的C++模板类型使运算符重载?
- 运算符重载使用运算符+添加类模板