C++ 可以使用cout将用户定义的类型自动转换为std::string吗?

C++ 可以使用cout将用户定义的类型自动转换为std::string吗?,c++,casting,stdstring,implicit-conversion,user-defined-types,C++,Casting,Stdstring,Implicit Conversion,User Defined Types,如问题所述,如果我在类中定义字符串运算符: class Literal { operator string const () { return toStr (); }; string toStr () const; }; 然后我用它: Literal l1 ("fa-2bd2bc3e0"); cout << (string)l1 << " Declared" << endl; Literal l1(“fa-2bd2bc3e0”); 不

如问题所述,如果我在类中定义字符串运算符:

class Literal {
  operator string const () {
    return toStr ();
  };

  string toStr () const;
};
然后我用它:

Literal l1 ("fa-2bd2bc3e0");
cout << (string)l1 << " Declared" << endl;
Literal l1(“fa-2bd2bc3e0”);

不能0。。string必须有一个以Literal作为参数的构造函数


您可以做的是重载操作符简短回答:继续使用cast或
toStr()
,或者编写自己的
操作符如果您计划将类用于流操作,您确实应该重载>操作符。它使用类清洁器。C++有自己的转换操作符集。不要使用c castsA转换构造函数和转换运算符在确定函数调用是否可行时是等效的。编译器不在此处执行隐式强制转换的真正原因更为复杂。@B示例代码仅将强制转换用作
Literal
(用户定义的类型)所需的字符串格式逻辑的占位符。在实践中,UDT可能有许多属性,每个属性都支持ostream操作符,聚合的ostream操作符只需将它们逐个追加。说得好!顺便说一句,这就是为什么运算符const char*(){}可以工作,而运算符string(){}不能工作的原因。
ostream &operator <<(std::ostream &stream, const Literal &rhs)
{
    stream << (string) rhs;
    return stream;
}
std::ostream& operator<<( std::ostream&, std::string const& );
// This is somewhat simplified.  For the real definitions, see the Standard
// and/or your complying implementation's headers.
namespace std {
  typedef basic_string<char> string;
  typedef basic_ostream<char> ostream;

  template <typename CharT>
  basic_ostream<CharT>& operator<<(
    basic_ostream<CharT>&, 
    basic_string<CharT> const&);
}