我有一个带字符串转换运算符的Foobar类:
#include <string>
class Foobar
{
public:
Foobar();
Foobar(const Foobar&);
~Foobar();
operator std::string() const;
};
Run Code Online (Sandbox Code Playgroud)
我试图像这样使用它:
// 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();
}
Run Code Online (Sandbox Code Playgroud)
我是否需要为Foobar明确创建一个运算符<<.我不明白为什么这是必要的,因为FooBar在放入iostream之前被转换为字符串,而std :: string已经有了operator << defined.
那么为什么这个错误呢?我错过了什么?
[编辑]
我刚刚发现,如果我改变了行,就会发生错误,对此:
ss << "Foobar is: " << fb.operator std::string();
Run Code Online (Sandbox Code Playgroud)
它编译成功.呃......!为什么编译器不能进行自动转换(Foobar - > string)?
什么是解决这个问题的"最佳实践"方法,所以我不必使用上面的丑陋语法?
Foobar fb在放入流之前不会转换为字符串.不要求<<运算符的参数必须是字符串.
您应该手动将其转换为字符串
ss << "Foobar is: " << std::string(fb);
Run Code Online (Sandbox Code Playgroud)
或者为Foobar定义一个运算符<<.
定义运算符<<将是明智之举,并且没有理由不能在运算符<<代码中调用字符串转换.
| 归档时间: |
|
| 查看次数: |
4553 次 |
| 最近记录: |