我必须使用模板,因为要求x、y、z可以是任何类型(int、float、double、long等)。
#include <conio.h>
#include <iostream>
using namespace std;
template <class T>
class TVector //this class is for creating 3d vectors
{
T x, y, z;
public:
TVector() //default value for x, y, z
{
x = 0;
y = 0;
z = 0;
}
TVector(T a, T b, T c)
{
x = a; y = b; z = c;
}
void output()
{
cout << x << endl << y << endl << z;
}
//overloading operator + to calculate the sum of 2 vectors (2 objects)
TVector operator + (TVector vec)
{
TVector vec1;
vec1.x = this->x + vec.x;
vec1.y = this->y + vec.y;
vec1.z = this->z + vec.z;
return vec1;
}
};
int main()
{
TVector<int> v1(5, 1, 33);
TVector<float> v2(6.11, 6.1, 5.1);
TVector<float> v3;
v3 = v1 + v2;
v3.output();
system("pause");
return 0;
}
如果对象
v1
如果是float,则上述代码将完美运行。然而,要求向量v1具有
内景
作为其数据类型。如何解决此问题?
我已经尝试使用模板重载+运算符,我的代码如下所示:
template <typename U>
TVector operator+(TVector<U> vec)
{
TVector vec1;
vec1.x = this->x + vec.x;
vec1.y = this->y + vec.y;
vec1.z = this->z + vec.z;
return vec1;
};
^仍然不起作用: