C++ ostream <<过载问题
C++ ostream << overloading problems
我们知道迷人的类iostream太强大了。它覆盖了插入运算符"<<"以采用许多数据类型:ostream& operator(ostream&, int(,ostream&operator(ostream&, char(...
我们无法实例化 ostream:ostream 打印;因为ostream,因为它的大多数CTOR都是"受保护的"(不能从外部访问(。
我们唯一可以调用的构造函数是 ostream(streambuf*(,它接受指向另一个类对象(类 streambuf(的指针;
我只是想搞砸这门课:
#include <ostream>
using namespace std;
int operator << (ostream& out, int* x)
{
out << "invoked!" << endl;
cout << *x; // works well!
cout << x; // normally works well and it prints the address that x points to but instead the program get in infinite loop or crushes!
return *x;
}
int main()
{
system("color 1f");
int* pVal = new int(57);
cout << *pVal << endl;
int* pX = new int(7);
cout << *pX << endl;
cout << *pVal << ", " << *pX << endl;
//cout << pVal << endl; // this doesn't work because my operator returns
//int and not a reference to ostream.
// and it is equal to: 0 << endl; which generates the same error
cout << pVal; // this works
// cout << endl << endl << endl;
return 0;
}
我重载了插入运算符以将左值作为对 ostream 对象的引用,并将指向 int 的指针作为 rvalue,我在函数中弹出一条消息以确保它被调用。
请注意,我故意重载它以返回 int 值,以便没有人可以编写:
out << pInt << *pInt << endl;
。但只是:
out << pInt;
正如您在上面的内联注释中看到的那样,我的问题是,虽然cout << x
通常运行良好,但程序反而陷入无限循环或粉碎!
return *x;
谁能解释为什么我收到错误?
发生此问题是因为如果您只是cout << x
,它将一遍又一遍地调用您的重载函数。它永远不会回来。
这是解决方案(将 x 转换为无效*(
int operator << (ostream& out, int* x)
{
out << "invoked!" << endl;
cout << *x; // works well!
cout << (void*)x;
return *x;
}
相关文章:
- 警告处理为错误这里有什么问题
- 最小硬币更换问题(自上而下方法)
- 为"adjacent"变量赋值时出现问题
- 我的神经网络不起作用 [XOR 问题]
- 在Ubuntu 16.04上安装Cilk时出现问题
- C++我的数学有什么问题,为什么我的代码不能正确循环
- 编译包含字符串的代码时遇到问题
- Project Euler问题4的错误解决方案
- 问题:什么是QAbstractItemView::NoEditTriggers的反面
- 在编译C++代码(具有dlib和opencv)到WASM时面临问题
- 在进程中对同一管道进行读取和写入时C++管道出现问题
- 静态数据成员的问题-修复链接错误会导致编译器错误
- C++ 雷神库 - 使用资源加载器类时出现问题(不命名类型)
- 请解释这句话(cout<<1+int((a<b)^((b-a)&1) )<<endl
- 一个关于在C++中重载布尔运算符的问题
- 首要问题的答案让值班员搞错了
- setlocale的C++土耳其字符串问题
- 如何重构类层次结构以避免菱形问题
- 呼叫运营商<<临时
- 基于boost的程序的静态链接——zlib问题