【问题标题】:Is possible to get automatic cast from user-defined type to std::string using cout?是否可以使用 cout 从用户定义的类型自动转换为 std::string?
【发布时间】:2010-10-22 19:39:46
【问题描述】:

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

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

  string toStr () const;
};

然后我使用它:

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

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

【问题讨论】:

    标签: c++ casting stdstring implicit-conversion user-defined-types


    【解决方案1】:

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

    您可以做的是为您的 Literal 类重载运算符

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

    【讨论】:

    • 如果你打算将你的类与流操作一起使用,你真的应该重载 > 操作符。它使使用类更清洁。
    • c++ 有它自己的一组转换运算符。不要使用 c 强制转换
    • 在确定函数调用是否可行时,转换构造函数和转换运算符是等效的。编译器不会在这里进行隐式转换的真正原因更复杂。
    • @BЈовић 示例代码仅使用强制转换作为Literal(用户定义类型)所需的字符串格式化逻辑的占位符。在实践中,UDT 可能有许多属性,每个属性都支持 ostream 运算符,而聚合的 ostream 运算符将简单地一一附加。
    【解决方案2】:

    简答:继续使用演员表或toStr(),或编写自己的operator&lt;&lt; 函数。 (比起(string)l1,我更喜欢l1.toStr()。)

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

    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 &lt;&lt; str,其中str的类型是std::string时,它可以计算出使用该模板函数,与CharT = char

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

    【讨论】:

    • 说得好!顺便说一句,这就是为什么 operator const char *(){} 起作用而 operator string(){} 不起作用的原因。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-08-17
    • 1970-01-01
    • 2018-05-07
    • 2011-03-31
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多