c ++ operator + =重载struct string

时间:2016-05-06 13:50:43

标签: c++ string struct operator-overloading

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

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

2 个答案:

答案 0 :(得分:4)

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

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

答案 1 :(得分:-1)

操作员+ =不需要返回值:

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;
}