C ++ Operator + =重载 [英] C++ Operator += overload

查看:1039
本文介绍了C ++ Operator + =重载的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想重载运算符+ =在我将使用它的方式a + = b;它将向向量a中添加b
在标题中有这样的:

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;

这是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

推荐答案

可以重载 + = / code>运算符使用成员函数或非成员函数。

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

当它是成员函数时,运算符的LHS是对象函数将被调用,而运算符的RHS是函数的参数。因此,成员函数的唯一参数是RHS。

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,你不需要使用 void Book :: operator + = ,只是 void operator + =

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

此外,更惯用的是使用

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

第一个的实现可以是:

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

,第二个可以是:

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

您可以看到 std :: vector documentation 了解这些操作的详细信息。

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

PS 不要混淆使用相同名称的输入参数的成员变量 a b

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

这篇关于C ++ Operator + =重载的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆