【问题标题】:c++ operator+= overloading struct stringc++ operator+= 重载结构字符串
【发布时间】:2016-05-06 13:50:42
【问题描述】:

在下面的程序中调用运算符 += 会产生分段错误。我不知道为什么。

#include <string>
struct foo
{
    std::string name;
    foo operator+=(  foo bar )
    {}
};
int main()
{
    foo a,b;
    a += b;
    return 0;
}

【问题讨论】:

  • 你需要从算子函数中返回一些东西。
  • 确保编译您的应用程序时打开所有警告,并将警告设置为错误。使用这个:g++ -Wall -Wextra -Werror -Wpedantic。这会告诉你问题出在哪里。
  • 编译器应该对此发出警告。
  • 我想知道为什么您的代码示例在没有非 void 函数返回时会编译!
  • 另外你的实现是错误的,应该有对从函数返回的实际实例的引用。

标签: c++ string struct operator-overloading


【解决方案1】:

没有返回语句可能会导致分段错误。您的实现应如下所示:

foo& operator+=( const foo& bar )
 {
   name += bar.name;
   return *this;
 }

【讨论】:

    【解决方案2】:

    运算符 += 不需要返回值:

    struct Test
    {
        std::string str;
        void operator += (const Test& temp);
    };
    
    void Test::operator += (const Test& temp)
    {
        str += temp.str;
        return;
    }
    
    int main()
    {
        Test test, test_2;
        test.str = "abc";
        test_2.str = "def";
        test += test_2;
        return 0;
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2011-03-15
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-01-05
      相关资源
      最近更新 更多