我有一个带有字符串转换运算符的 Foobar 类:
#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 -> 字符串)?
解决此问题的“最佳实践”方法是什么,这样我就不必使用上面丑陋的语法了?
最佳答案
Foobar fb 在放入您的流之前不会转换为字符串。不要求 << 运算符的参数必须是字符串。
您应该手动将其转换为字符串
ss << "Foobar is: " << std::string(fb);
或者为 Foobar 定义一个运算符<<。
定义一个运算符<< 是明智的选择,没有理由不在运算符<< 代码中调用字符串转换。
关于c++ - 在 std::operator << [With _Traits = std::char_traits<char> ] 中不匹配 'operator <<',我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4848760/