C++中,可以定义类模板。
#include <iostream>
using namespace std;
template <class T>
class Vector {
public:
Vector(int);
~Vector();
Vector(const Vector&);
Vector& operator=(const Vector& rhs);
T& operator[](int);
void print() { cout << "print()" << endl; }
private:
T* m_elements;
int m_size;
};
template <class T>
Vector<T>::Vector(int size) :m_size(size) {
cout << "this is constructor" << endl;
cout << this->m_size << endl;
m_elements = new T[m_size];
}
template <class T>
Vector<T>::~Vector() {
cout << "this is Destrucor" << endl;
delete[] m_elements;
m_elements = NULL;
}
template<class T>
Vector<T>::Vector(const Vector &)
{
cout << "this is copy construcor" << endl;
}
template <class T>
Vector<T>& Vector<T>::operator=(const Vector& rhs) {
cout << "this is = " << endl;
//*this = rhs;
return *this;
}
template <class T>
T& Vector<T>::operator[](int index) {
if (index>=0 && index<m_size) {
return m_elements[index];
}
else {
cout << "index is invalid" << endl;
}
}
int main()
{
Vector<int> v1(6);
Vector<double> v2(2);
v2[0] = 11.1;
cout << "v1[0]: "<<v1[0] << endl;
cout <<"v2[0]:"<< v2[0] <<" v2[1]: "<<v2[1]<< endl;
cout << "hello" << endl;
int i = 1;
for (; i < 6; i++) {
v1[i] = i;
}
cout << typeid(v2[1]).name() << endl;
cout << i << endl;
return 0;
}