【问题标题】:operator std::string() const?运算符 std::string() 常量?
【发布时间】:2011-03-03 22:45:27
【问题描述】:

谁能告诉我具体是什么

operator std::string()

代表什么?

【问题讨论】:

    标签: c++ operator-keyword


    【解决方案1】:

    这是一个conversion operator,它允许将对象显式或隐式转换为std::string。当发生这种转换时,将调用运算符,转换的结果就是调用的结果。

    作为隐式转换的示例,假设您有一个接受类型 std::stringconst std::string& 的函数,但不接受给定的对象类型。将您的对象传递给该函数将导致调用转换运算符,并将结果传递给函数而不是您的类型。

    【讨论】:

      【解决方案2】:

      它是一个强制转换运算符。任何定义此类型的类都可以在需要std::string 的任何地方使用。例如,

      class Foo {
      public:
          operator std::string() const { return "I am a foo!"; }
      };
      ...
      Foo foo;
      std::cout << foo; // Will print "I am a foo!".
      

      强制转换运算符几乎总是一个坏主意,因为总是有更好的方法来实现相同的结果。在上述情况下,您最好定义operator&lt;&lt;(std::ostream&amp;, const Foo&amp;)

      【讨论】:

      • 我反对“总是”这个词,它太绝对了。我认为“通常”是一个更好的词。
      • Loki,你自己的评论太绝对了。一个人应该总是避免使用“总是”这个词,还是应该通常避免使用“总是”这个词?
      • 事情变得自相矛盾
      • 您不需要将 foo 类型转换为 (string)foo 吗?
      • @poorva 你是对的,@MarceloCantos 你错了:在这种情况下你确实需要将它显式转换为字符串,否则你会得到一个错误error: cannot bind ‘std::ostream {aka std::basic_ostream&lt;char&gt;}’ lvalue to ‘std::basic_ostream&lt;char&gt;&amp;&amp; 原因是@ 987654325@ 被定义为模板函数,因此必须对其参数完全匹配,并且隐式转换不相关。
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2023-03-21
      • 1970-01-01
      • 2017-06-06
      • 2016-05-02
      相关资源
      最近更新 更多