【发布时间】: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
知道我做错了什么吗?
【问题讨论】:
-
There are too many unrelated errors 运行代码时。请先修复这些错误并提供minimal, reproducible example。
标签: c++ vector operator-overloading template-classes