正如在问题,如果我在类中定义的字符串操作符:

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

  string toStr () const;
};

和然后我使用它:

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

有一个明确的投一切正常,但如果我删除(字符串)编译器说,它需要的std :: string声明转换运算符。难道不应该自动投我喜欢的类型? 解决:我重载operator <<(ostream的和OS,常量立即数&L)

有帮助吗?

解决方案

没有..的std :: string就必须有一个把文字作为参数的构造函数。

你可以做的是超负荷运营商<<你的文字类,并有将它转换并插入到在那里流。

ostream &operator <<(std::ostream &stream, const Literal &rhs)
{
    stream << (string) rhs;
    return stream;
}

其他提示

简短的回答:继续使用浇注或者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 << str其中str的类型是std::string,它可以计算出以使用模板函数,与CharT = char

但是C ++不允许有对同一呼叫编译器弄清楚两者隐式类型转换(Literalstring)和演绎模板函数模板参数(CharT = char)。

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top