重载<<使用ostream的运算符不起作用。为什么?

时间:2016-07-15 10:03:03

标签: c++

我有一个小代码片段试图重载“<<” std :: cout的运算符。

#include<iostream>
using namespace std;

ostream& operator<<(ostream& out,const string& str)
{
    out << "overloading" << str << "done";
    return out;
}

int main()
{
    cout << "string123";
}

输出:string123。 看来我的重载功能没有被调用。为什么呢?

3 个答案:

答案 0 :(得分:1)

首先,您不是std::string,而是const char*。您可以通过编写cout << std::string("string123")来代替demo;但是,ew)。

请注意<string>已经存在这样的重载,您的实施显然恰好包括<string><iostream>as does mine,并且它的特权也是如此)。但是,您的版本(在进行上述修复之后)是一个更好的匹配,因为不需要调用ADL来查找它。

答案 1 :(得分:1)

您应该将字符串类型发送到<<

ostream& operator<<(ostream& out,const string& str)
{
    out<<"overloading";
    return out;
}

int main()
{
    string s = "string123";
    cout << s;
}

请注意,在<<定义中再次发送字符串本身将为

进行无限递归
out << "overloading" << str <<"done"

答案 2 :(得分:1)

你基本上是在你的榜样中射击自己。您为operator<<类型重载std::string,因此每次尝试发送&#34; std :: string&#34时都应该调用它。到out,从而导致运行时堆栈过低。为了使它成功,你:

  • 需要在char *重载中将out类型输出到operator<<,因此它不会导致无限递归
  • std::string中发送实际main

这是一个没有运行时堆栈溢出问题的工作示例:

#include<iostream>
using namespace std;
ostream& operator<<(ostream& out, const string& str)
{
    out << "overloading" << str.c_str() << "done";
    return out;
}

int main()
{
    cout << std::string("string123");
}

输出

overloadingstring123done