隐式转换为std :: string [英] Implicit conversion to std::string
问题描述
可能重复:
通过隐式转换流对象时,重载分辨率失败字符串
Possible Duplicate:
Overload resolution failure when streaming object via implicit conversion to string
我知道这样做不是一个好主意,但是我真的很想知道以下代码为何无法编译的原因(即为什么没有可接受的转换"):
I know it's not such a good idea to do this, but I really want to know the reason why the code below does not compile (i.e. why there is "no acceptable conversion"):
#include <iostream>
#include <string>
class Test
{
public:
operator std::string () const;
};
Test::operator std::string () const
{
return std::string("Test!");
}
int main ()
{
std::string str = "Blah!";
std::cout << str << std::endl;
Test test;
str = test;//implicitly calls operator std::string without complaining
std::cout << str << std::endl;
std::cout << test;//refuses to implicitly cast test to std::string
return 0;
}
在Visual Studio 2010上,我收到此错误:"error C2679: binary '<<' : no operator found which takes a right-hand operand of type 'Test' (or there is no acceptable conversion)
"
On Visual Studio 2010 I get this error: "error C2679: binary '<<' : no operator found which takes a right-hand operand of type 'Test' (or there is no acceptable conversion)
"
<<
运算符是否可以将std::string
隐式转换为其他内容以便使用?如果是,我需要在类中重载什么运算符才能使此功能正常工作?我拒绝相信我实际上需要使用operator char *
.
Does the <<
operator implicitly cast std::string
to something else in order to make use of it? If yes, what operator do I need to overload in my class to make such a thing work? I refuse to believe that I would actually need to use operator char *
.
推荐答案
operator<<(std::basic_ostream&, std::basic_string)
是函数模板,在模板自变量推导过程中不考虑用户定义的转换.您需要在课程中重载operator<<
.
operator<<(std::basic_ostream&, std::basic_string)
is a function template and user defined conversions are not considered during template argument deduction. You need to overload operator<<
for your class.
当然,另一个选择是强制转换
Another option, of course, is a cast
std::cout << static_cast<std::string>(test);
这篇关于隐式转换为std :: string的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!