简体   繁体   中英

c++ operator+= overloading struct string

Calling the operator += in the programm below produces a segmentation fault. I have no idea why.

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

Having no return statement might cause segmentation fault. Your implementation should look as follows:

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

Operator += don't need to return a value:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM