c++ - 在 std::operator << [With _Traits = std::char_traits<char> ] 中不匹配 'operator <<'

标签 c++

我有一个带有字符串转换运算符的 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/

相关文章:

c++ - 如何在 C++ 函数中将静态数组初始化为某个值?

c++ 如何处理返回 NULL 或 std::string 的方法?

c++ - 如何在 C++ 中启用共享打开的文件?

c++ - 如何根据元素数量选择 max_load_factor?

c++ - 使用函数中的语句数作为常量进行内存分配

c++ - 在 C++ 中评估基于矩阵的多项式的最佳方法

c++ - 理解 std::function 和 std::bind

c++ - 合并排序字符串

C++三角形光栅化

c++ - 在 C++ 中制作简单的跨平台 GUI 的最佳方法是什么?