C++ Operator += overload

2019-08-26 02:50发布

问题:

I want to overload the operator += in the way that when i will use it a+=b; it will add b to the vector a having this in the header:

public:
...
void Book::operator+=(std::string a, std::vector<std::string>>b);
private:
...
    std::string b;
    stf::vector<std::string> a;

this is the implementation in cpp

void Book::operator+=(std::string a, std::vector<std::string>>b)
{
b.push_back(a);
}

What can be my error? It is not clear for me the use of overload operators yet

回答1:

You can overload the += operator using a member function or a non-member function.

When it is a member function, the LHS of the operator is the object on which the function will be called and RHS of the operator is the argument to the function. Hence, the only argument to the member function will be the RHS.

In your case, you have two arguments. Hence, it is wrong. You can use:

void operator+=(std::string a);
void operator+=(std::vector<std::string>>b);

or something like that where there is only one argument in the member function.

BTW, you don't need to use void Book::operator+=, just void operator+=.

Also, it is more idiomatic to use

Book& operator+=(std::string const& a);
Book& operator+=(std::vector<std::string>> const& b);

The implementation of the first one could be:

Book& operator+=(std::string const& aNew)
{
   b.push_back(aNew);
   return *this;
}

and that of the second one could be:

Book& operator+=(std::vector<std::string>> const& bNew);
{
   b.insert(b.end(), bNew.begin(), bNew.end());
   return *this;
}

You can see std::vector documentation for details on these operations.

PS Don't confuse member variables a and b with input arguments of the same name.