刚接触类的相关内容,完成了简单的Vector模板类的项目。
用template <class T>来实现n维向量的相关性质。
写的时候其中有几个关键的地方
1.模板类的函数定义必须和头文件放在一个cpp文件里,系统不支持模板类的单独编译。
2.定义模板类的成员(友元)函数时,都要加 template <class T> or template <typename T>。
3.对于模板类的友元函数,都声明成了非约束(unbound)模板友元。 ( 详见参考blog)
4.缺陷在于没有更细致的了解模板以及没有添加异常处理等情况。
以下简单代码实现
//vector.h
#ifndef vector_h
#define vector_h
#include <algorithm>
#include <cstring>
#include <math.h>
#include "vector.h"
#include<iostream>
using namespace std;
template<class T>
class vector
{
public:
vector();
vector(vector<T> &temp);
~vector(){if(array !=NULL) delete array;}
vector & operator=(const vector<T>& temp);
template <typename TYPE> friend vector<TYPE> operator+(vector<TYPE> &temp1,vector<TYPE> &temp2);
template <typename TYPE> friend vector<TYPE> operator-(vector<TYPE> &temp1,vector<TYPE> &temp2);
T Find(T& temp);
T operator*(vector<T> &temp);
T norm (vector<T> &temp);
vector & unit(vector<T> &temp);
template <typename TYPE> friend vector<TYPE> Vector_Cross_Product(vector<TYPE> &temp1,vector<TYPE> &temp2);
template <typename TYPE> friend bool Perpendicular(vector<TYPE> &temp1,vector<TYPE> &temp2);
template <typename TYPE> friend bool Parallel(vector<TYPE> &temp1,vector<TYPE> &temp2);
template <typename TYPE> friend ostream & operator<<(ostream &out, const vector<TYPE> &temp);
template <typename TYPE> friend istream & operator>>(istream &in,vector<TYPE> &temp);
protected:
T *array;
int len;
int sum;
};
//0.默认构造函数
template <class T>
vector<T&g