c++ - 在具有 2 个模板的模板类中重载 operator+

标签 c++ c++11 templates operator-overloading

我有以下模板:

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/

相关文章:

c++ - 使用 C++ 在 Qt Creator 中创建 QLabel 的子类

c++ - 有没有办法将 void (*)(uint32_t, void (*)(uint32_t)) 转换为 std::function<void(uint32_t, std::function<void(uint32_t)>)>?

c++ - 模板类嵌套类型 typename

C++ 部分模板特化语法

c++ - 如何向 C++ 应用程序添加反射?

c++ - 指向类数据成员 "::*"的指针

c++:如何编写一个类似 std::bind 的对象来检查多余的参数?

c++ - 错误 : conversion from 'const char [10]' to non-scalar type 'std::fstream {aka std::basic_fstream<char>}' requested

C++使用 map 查找出现次数最多的字符

c++ - 为什么成员变量被 "all automatic"捕获,而不是显式命名?