我有以下模板:
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;
}
关于c++ - 在具有 2 个模板的模板类中重载 operator+,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59421050/