不匹配 '运算符<<' 中的std ::运营商<< [随着_Traits =标准:: char_traits ]

问题描述:

我有串转换操作符类的Foobar:不匹配 '运算符<<' 中的std ::运营商<< [随着_Traits =标准:: char_traits <char>]

#include <string> 

class Foobar 
{ 
public: 
    Foobar(); 
    Foobar(const Foobar&); 
    ~Foobar(); 

    operator std::string() const; 
}; 

我尝试使用它像这样:

// C++源文件

#include <iostream> 
#include <sstream> 
#include "Foobar.hpp" 

int main() 
{ 
    Foobar fb; 
    std::stringstream ss; 

    ss << "Foobar is: " << fb; // Error occurs here 

    std::cout << ss.str(); 
} 

我需要明确的创建操作< <为Foobar的?我不明白为什么这是必要的,因为FooBar在被放入iostream之前被转换为字符串,并且std :: string已经定义了运算符< <。

那么为什么这个错误呢?我错过了什么?

[编辑]

我发现,如果我改了行发生错误的情况,这样:

ss << "Foobar is: " << fb.operator std::string(); 

它编译成功。呃......!为什么编译器不能自动转换(Foobar - > string)?

什么是解决这个问题的“最佳实践”方法,所以我不必使用上面丑陋的语法?

+0

http://stackoverflow.com/q/6677072/560648? – 2014-06-08 18:20:27

在放入流中之前,Foobar fb未转换为字符串。不要求运算符的参数必须是字符串。

您应该将它转换为字符串手动

ss << "Foobar is: " << std::string(fb); 

或定义操作< <为Foobar的。

定义一个运营商< <将是明智的选择,并且没有理由不能在您的运营商< <代码中调用您的字符串转换。