[英]c++ Operator overloading for template vector struct
I am creating a template Vector<T,n>
struct and trying to overload some arithmetic operations.我正在创建一个模板
Vector<T,n>
结构并尝试重载一些算术运算。 However, even when I did overload the operators, I'm getting no match errors.但是,即使我确实使运算符过载,也没有出现匹配错误。 Code shown below.
代码如下所示。
In my Vector.hpp
file I have the following code:在我的
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;
And in Vector.cpp
:在
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;
}
However, when I invoked this operator in main, it won't compile:但是,当我在 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;
}
Here's the error message:这是错误消息:
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
Any idea on what I'm doing wrong?知道我做错了什么吗?
Since addition is a binary operator you need to supply two arguments to overload it.由于加法是一个二元运算符,您需要提供两个参数来重载它。 Furthermore, if your addition operator should be commutative, it should be implemented as a non-member.
此外,如果您的加法运算符应该是可交换的,则应将其实现为非成员。
Here is a working example:这是一个工作示例:
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)
}
};
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.