我正在尝试创建一个通用的向量类,既是为了我的代码片段库,也是为了练习模板类。 本质上,向量类是模板化的,允许您选择其精度为float、double、long double等。
我遇到的问题是重载*运算符以缩放向量。去除所有正常工作的重载和成员函数后,类定义如下:
#pragma once
#include <math.h> // for sqrt function when normalizing
template <typename T> class Vector;
template <typename T> Vector<T> operator*(const Vector<T>& obj);
template <typename T> class Vector {
private:
// Attributes:
static const int DIMS = 3;
T component[DIMS];
public:
enum {
X, Y, Z
};
public:
// Constructors:
Vector(void) {
for (int i=0; i<DIMS; ++i) {
component[i] = T();
}
}
Vector(T x, T y, T z) {
component[X] = x;
component[Y] = y;
component[Z] = z;
}
// Destructor:
~Vector(void) { }
// Scaling:
friend Vector<T> operator*(const Vector<T>& obj);
Vector operator*(const T scale) {
Vector<T> result = Vector<T>();
for (int i=0; i<DIMS; ++i) {
result.component[i] = component[i] * scale;
}
return result;
}
};
template <typename T>
Vector<T> operator*(const Vector<T>& obj) {
Vector<T> result = Vector<T>();
for (int i=0; i<DIMS; ++i) {
result.component[i] = obj.component[i] * this*;
}
return result;
}
在我的主方法中,我有以下代码行: ```java ```
Vector<float> testVector1 = Vector<float>(1.0f, 0.0f, 0.0f);
Vector<float> testVector2 = Vector<float>(0.0f, 1.0f, 0.0f);
Vector<float> testVector3 = 10.0f * testVector1;
Vector<float> testVector4 = testVector2 * 10.0f;
除了一个错误,一切都编译正常:在main()函数中,第四行(将向量乘以标量)可以正常工作,但第三行(将标量乘入向量)却给我报错:
错误 1 error C2677: binary '*' : no global operator found which takes type 'Vector<T>' (or there is no acceptable conversion)
我对这个问题的最佳猜测是编译器不知道我试图重载哪个基本类型的*运算符,而我无法直接告诉它,因为在模板被传递到类之前,类不会知道类型。有没有办法实现我想做的事情,或者模板必须始终跟随类进行运算符重载?
更新: 感谢jwismar和其他人指出的错误左手重载尝试。现在类内部函数的定义为:
friend Vector<T> operator*(T scalar, const Vector<T>& obj);
它的实现方式是:
template <typename T>
Vector<T> operator*(T scalar, const Vector<T>& obj) {
Vector<T> result = Vector<T>();
for (int i=0; i<DIMS; ++i) {
result.component[i] = obj.component[i] * scalar;
}
return result;
}
在类之上的重载初始声明现在是
template <typename T> Vector<T> operator*(T scalar, const Vector<T>& obj);
,然而无论是否将其注释掉,我都得到了相同的错误。现在我面临一个更具体的问题,涉及模板和运算符重载。尽管错误现在是未解决的外部调用,编译器仍然不予通过:
Error 1 error LNK2019: unresolved external symbol "class Vector<float> __cdecl operator*(float,class Vector<float> const &)" (??D@YA?AV?$Vector@M@@MABV0@@Z) referenced in function _main C:\Users\D03457489\Desktop\UVCTester\UVCTester\main.obj UVCTester
因此编译器告诉我它能够找到 operator*(float, Vector<float>)
的定义,但找不到实现。那么新的问题是:这是我的另一个基本疏忽的结果,还是使用模板以这种方式生成运算符重载不可能使操作数左侧的结果未知?