【问题标题】:c++ Operator overloading for template vector struct模板向量结构的c ++运算符重载
【发布时间】:2020-06-25 01:46:14
【问题描述】:

我正在创建一个模板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

知道我做错了什么吗?

【问题讨论】:

标签: c++ vector operator-overloading template-classes


【解决方案1】:

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

这是一个工作示例:

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 偷走了。

【讨论】:

    猜你喜欢
    • 2021-02-20
    • 1970-01-01
    • 2012-09-29
    • 1970-01-01
    • 2018-05-20
    • 2013-11-10
    • 1970-01-01
    • 1970-01-01
    • 2020-03-09
    相关资源
    最近更新 更多