在具有 2 个模板的模板类中重载运算符+

Overloading operator+ in a template class with 2 templates

本文关键字:重载 运算符      更新时间:2023-10-16

我有以下模板е:

template <typename T1, typename T2>
class equationSolution {
public:
T1 a, b, c;
float d;

friend ostream& operator<< <T1, T2>(ostream& str, const equationSolution<T1, T2>& ov);
equationSolution<T1,T2>& operator+=(const equationSolution<T1, T2>& ov, const int& value);
equationSolution() : a(0), b(0), c(0) {}
equationSolution(T1 a1, T1 b1, T1 c1) : a(a1), b(b1), c(c1) {
a = a;
b = b;
c = c;
d = pow(b, 2) - 4 * a * c;
}
}

我设法使输出过载

template <typename T1, typename T2>
ostream& operator<<(ostream& str, const equationSolution<T1, T2>& ov)
{
str << "(" << ov.a << "," << ov.b << "," << ov.c << ")";
return str;
}

但是对于操作员+=我遇到了困难。 这就是我所做的:

friend equationSolution<T1, T2>& operator += (const equationSolution<T1, T2>& ov, const int& value) {
ov.a += value;
ov.b += value;
ov.c += value;
return ov;
}

但我有错误:

binary "operator + =" has too many parameters

所有赋值运算符重载(所有重载(都必须是成员函数,因此它们应该只接受一个参数:运算符的右侧。

也就是说,一个表达式,如

foo += bar;

将翻译为

foo.operator+=(bar);

将运算符函数声明为成员函数,但使用两个参数。然后,将函数定义为非成员friend函数,这是不允许的。您提到的错误来自声明。

你应该做的是这样的

equationSolution& operator+=(const int& value)
{
// TODO: Implement the actual logic
return *this;
}