模板向量结构的 C++ 运算符重载

c++ Operator overloading for template vector struct

我正在创建模板 Vector<T,n> 结构并尝试重载一些算术运算。但是,即使我确实超载了运算符,我也没有收到匹配错误。代码如下所示。

在我的 Vector.hpp 文件中,我有以下代码:

template <typename T, int n>
struct Vector
{
    T data[n];

    template <typename S>
    Vector<T, n> operator+(Vector<S, n> &vec);

    ...

}

typedef Vector<int, 3> vec3i;

Vector.cpp中:

template <typename T, int n>
template <typename S>
Vector<T, n> Vector<T, n>::operator+(Vector<S, n> &vec)
{
    T arr[n];
    for (int i = 0; i < n; i++)
    {
        arr[i] = this->data[i] + (T)vec->data[i];
    }
    Vector<T, n> result(arr);
    return result;
}

但是,当我在 main 中调用这个运算符时,它不会编译:

int main(int argc, char const *argv[])
{
    vec3i vec1 = Vec3i(1,2,3);
    vec3i vec2 = Vec3i(4,5,6);
    vec3i vec3 =  vec1 + vec2;
    std::cout << vec3.x << "," << vec3.y << "," << vec3.z <<"\n";
    return 0;
}

错误信息如下:

no operator "+" matches these operands -- operand types are: vec3i + vec3i
no match for ‘operator+’ (operand types are ‘vec3i {aka Vector<int, 3>}’ and ‘vec3i {aka Vector<int, 3>}’)GCC
no match for ‘operator+’ (operand types are ‘vec3i {aka Vector<int, 3>}’ and ‘vec3i {aka Vector<int, 3>}’)GCC

知道我做错了什么吗?

由于加法是二元运算符,因此您需要提供两个参数来重载它。此外,如果您的加法运算符应该是可交换的,则应将其实现为非成员。

这是一个工作示例:

class X
{
 public:
  X& operator+=(const X& rhs) // compound assignment (does not need to be a member,
  {                           // but often is, to modify the private members)
    /* addition of rhs to *this takes place here */
    return *this; // return the result by reference
  }

  // friends defined inside class body are inline and are hidden from non-ADL lookup
  friend X operator+(X lhs,        // passing lhs by value helps optimize chained a+b+c
                     const X& rhs) // otherwise, both parameters may be const references
  {
    lhs += rhs; // reuse compound assignment
    return lhs; // return the result by value (uses move constructor)
  }
};

我无耻地从 here.

那里偷了