C++ Operator += overload

匿名 (未验证) 提交于 2019-12-03 01:26:01

问题:

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.



标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!