【问题标题】:How to get MyClass to work with std::string's operator+如何让 MyClass 与 std::string operator+ 一起工作
【发布时间】:2012-12-05 06:44:54
【问题描述】:

我尝试了隐式转换,但这不起作用。

#include <string>
#include <iostream>

struct MyClass
{
    operator std::string() { return "bar"; }
};

int
main( int argc, char* argv[] )
{
    MyClass x;

    std::cout << std::string( "foo" ) + x << std::endl;
    return 0;
}

【问题讨论】:

  • 隐式转换不起作用,因为字符串的operator+ 是模板化的。
  • @Pubby 你应该回答这个问题!
  • +1 @Pubby 我同意!详细的解释将有助于我们所有人更好地理解 c++

标签: c++ operator-overloading implicit-conversion stdstring


【解决方案1】:

隐式转换不起作用,因为字符串的operator+ 是模板化的,并且您正在推断模板参数。这似乎是对正在发生的事情的更好解释:https://stackoverflow.com/a/8892794/964135

我只会做一个演员表或写一个非模板operator+


一个愚蠢的解决方案是不推断类型,然后它会进行隐式转换:

std::cout << std::operator+<char, std::char_traits<char>, std::allocator<char> >(std::string( "foo" ), x) << std::endl;

【讨论】:

    【解决方案2】:

    您是否尝试过重载 + 运算符?

    std::string operator+(std::string& str, MyClass& x){
        return str + "bar"
    } 
    

    这将是一个免费功能,而不是 MyClass 的一部分。此外,可能还需要重载可交换情况。没关系的可以用上面那个来表达。

    【讨论】:

      【解决方案3】:

      对于 Karthik T 和 Pubby 给出的关于重载 operator+() 的好答案,我想补充一点。

      通常,您需要在重载的 operator+() 代码中访问 MyClass 的私有成员(与您可能被剥离的示例中的 return "bar"; 不同)。在这种情况下,您需要将其声明为friend。您不能将operator+() 作为MyClass 的成员,因为MyClass 位于运算符+ 的左侧。请参考下面的示例代码。

      #include <string>
      #include <iostream>
      using namespace std;
      
      struct MyClass {
      public:
          MyClass() : bar("bar") {}
          friend string operator+(string& str, MyClass& x);
      private:
          string bar;
      };
      
      string operator+(string& str, MyClass& x) {
          return str + x.bar;
      }
      
      int main( int argc, char* argv[] )
      {
          MyClass x;
          string foo("foo");
      
          std::cout <<  foo + x << std::endl;
          return 0;
      }
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2021-12-10
        • 2014-03-29
        • 2011-09-06
        • 2016-12-05
        • 1970-01-01
        • 2023-02-02
        • 1970-01-01
        相关资源
        最近更新 更多