C++ 运算符 += 重载
C++ Operator += overload
我想以使用 a+=b 的方式重载运算符 +=;它会将 b 添加到向量 a
在 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);
}
我的错误是什么?我还不清楚重载运算符的使用
您可以使用成员函数或 non-member 函数重载 +=
运算符。
当它是一个成员函数时,运算符的左轴是调用函数的对象,运算符的右轴是函数的参数。因此,成员函数的唯一参数将是 RHS。
在你的例子中,你有两个参数。因此,这是错误的。您可以使用:
void operator+=(std::string a);
void operator+=(std::vector<std::string>>b);
或者类似的东西,成员函数中只有一个参数。
顺便说一句,你不需要使用 void Book::operator+=
,只需 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了解这些操作的详细信息。
PS 不要将成员变量 a
和 b
与同名输入参数混淆。
我想以使用 a+=b 的方式重载运算符 +=;它会将 b 添加到向量 a 在 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);
}
我的错误是什么?我还不清楚重载运算符的使用
您可以使用成员函数或 non-member 函数重载 +=
运算符。
当它是一个成员函数时,运算符的左轴是调用函数的对象,运算符的右轴是函数的参数。因此,成员函数的唯一参数将是 RHS。
在你的例子中,你有两个参数。因此,这是错误的。您可以使用:
void operator+=(std::string a);
void operator+=(std::vector<std::string>>b);
或者类似的东西,成员函数中只有一个参数。
顺便说一句,你不需要使用 void Book::operator+=
,只需 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了解这些操作的详细信息。
PS 不要将成员变量 a
和 b
与同名输入参数混淆。