调用 cout 时如何在结构中输出常量文本?
How I can output a constant text in struct when call cout?
我有这个结构:
struct sample {
int x;
};
然后我有这个运算符重载<<:
std::ostream &operator<<(const std::ostream &os, const sample &s) {
if (s.x == 0)
return os << "zero";
else
return os << "not zero";
}
主要:
int main() {
sample sam;
sam.x = 0;
std::cout << sam << std::endl;
sam.x = 1;
std::cout << sam << std::endl;
return 0;
}
但是编译器给了我这个错误: 编译错误
我能做什么?
你是对的,除了你的操作员签名中的一个小错误:
std::ostream &operator<<(const std::ostream &os, const sample &s)
// ^^^^^ Problem
将输出流标记为const
,然后在函数中对其进行修改:
os << "zero";
和
os << "not zero";
因为
std::basic_ostream<CharT,Traits>::operator<<
不是const
.
因此,删除该const
,代码将起作用。
相关文章:
- #定义c-预处理器常量..我做错了什么
- 递归函数计算序列中的平方和(并输出过程)
- 如何使用 < 和 > 命令获取 c++ 中的输入和输出?
- 用C++中的一个变量定义一个常量
- 什么时候在C++中返回常量引用是个好主意
- 请解释"函数1(p1,p2,p3);"的输出
- 代理对象的常量正确性
- 我想将一个对T类型的非常量左值引用绑定到一个T类型的临时值
- 调用 cout 时如何在结构中输出常量文本?
- 输出常量字符 * 带分隔符
- 为什么 c_str() 在返回常量指针值时不输出地址
- 在 C++ 中从字符串转换为常量字符*时出现奇怪的输出
- Cout 在循环访问常量字符时提供垃圾输出
- 尝试使用freopen创建输出文件,使用非常量字符串
- 指向常量作为输出参数 c++ 的指针
- 从指针检索字符串时获取常量空行输出
- 常量引用行为 - 为什么会出现此输出
- 如何从函数中获取替代值,该函数通过非常量输出参数提供所需数据,以便为其分配对常量变量的引用
- Ncurses 输出函数只接受常量数据
- 如何在Visual c++编译期间输出编译时数字常量?