C++ ostream <<过载问题

C++ ostream << overloading problems

本文关键字:lt 问题 ostream C++      更新时间:2023-10-16

我们知道迷人的类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;
}