3

在问题中,如果我在我的类中定义一个字符串运算符:

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

  string toStr () const;
};

然后我使用它:

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

使用显式强制转换一切正常,但是如果我删除(字符串),编译器会说它需要在 std::string 中声明的强制转换运算符。它不应该自动转换我的类型吗?已解决:我正在重载 operator<< (ostream& os, const Literal& l)。

4

2 回答 2

10

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

您可以做的是为您的 Literal 类重载运算符 << 并将其转换并插入其中的流中。

ostream &operator <<(std::ostream &stream, const Literal &rhs)
{
    stream << (string) rhs;
    return stream;
}
于 2010-10-22T19:43:09.003 回答
5

简短回答:继续使用强制转换或toStr(),或编写自己的operator<<函数。(我更愿意l1.toStr()(string)l1

长答案:如果标准库有一个函数,这可能会起作用

std::ostream& operator<<( std::ostream&, std::string const& );

它几乎可以做到,但在技术上不是。两者ostreamstring都是模板实例化的类型定义。还有一个模板函数可以将一个插入另一个。

// 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&);
}

因此,当您使用cout << strwhere 的类型时strstd::string它可以计算出使用该模板函数,与CharT = char.

但是 C++ 不允许您让编译器在同一个调用中找出隐式类型转换 ( Literalto string) 和推断模板函数模板参数 ( CharT = char)。

于 2010-10-22T20:14:34.870 回答