练习编写了一个vector类模板,代码记录在这里吧。
/*
test.h
*/
#pragma once
#include <iostream>
using namespace std;
template <typename T>
class Array
{
public:
Array(int m_len);
Array(const Array &a);
~Array();
public:
T & operator[](int index);
Array & operator=(const Array &a);
friend ostream & operator<< <T>(ostream & out, const Array &a);
private:
int len;
T *space;
};
template <typename T>
Array<T>::Array(int m_len)
{
len = m_len;
space = new T[len];
}
//拷贝构造函数,初始化变量的时候调用
template <typename T>
Array<T>::Array(const Array<T> &a)
{
len = a.len;
space = new T[len];
for (int i = 0; i < len; i++)
{
space[i] = a.space[i];
}
}
template <typename T>
Array<T>::~Array()
{
cout << "析构函数被调用" << len << endl;
}
template <typename T>
T & Array<T>::operator[](int index)
{
return space[index];
}
//等号运算符重载,需要清空左值
template <typename T>
Array<T> & Array<T>::operator=(const Array<T> &a)
{
if (space != NULL)
{
delete[] space;
space = NULL;
}
len = a.len;
space = new T[len];
for (int i = 0; i < len; i++)
{
space[i] = a[i];
}
return *this;
}
template <typename T>
ostream & operator<<(ostream & out, const Array<T> &a)
{
for (int i = 0; i < a.len; i++)
{
out << a.space[i] << endl;
}
return out;
}
/*
test.cpp
*/
#include <iostream>
#include "test.h"
using namespace std;
class Teacher
{
public:
Teacher();
Teacher(int age, const char * name);
Teacher(const Teacher & t);
~Teacher();
public:
//operator[](int index);
Teacher & operator=(const Teacher & t);
friend ostream & operator<< (ostream & out, const Teacher & t);
private:
int age;
char * name;
};
Teacher::Teacher()
{
age = 0;
name = new char[1];
strcpy(name, "");
}
Teacher::Teacher(int age, const char * name)
{
this->age = age;
this->name = new char[strlen(name) + 1];
strcpy(this->name, name);
}
Teacher::Teacher(const Teacher & t)
{
age = t.age;
name = new char[strlen(t.name) + 1];
strcpy(name, t.name);
}
Teacher::~Teacher()
{
delete[] name;
name = NULL;
age = 0;
}
Teacher & Teacher::operator=(const Teacher & t)
{
if (name != NULL)
{
delete[] name;
name = NULL;
}
age = t.age;
name = new char[strlen(t.name) + 1];
strcpy(name, t.name);
return *this;
}
ostream & operator<< (ostream & out, const Teacher & t)
{
out << t.name << endl;
return out;
}
int main(void)
{
//T = int
Array<int> a1(10);
for (int i = 0; i < 10; i++)
{
a1[i] = i * i;
}
cout << a1 << endl;
//T = char
Array<char> a2(10);
for (int i = 0; i < 10; i++)
{
a2[i] = 'a';
}
cout << a2 << endl;
//T = class
Array<Teacher> a3(10);
Teacher t1, t2(25, "sssss"), t3(38, "xxxxx");
a3[0] = t1;
a3[1] = t2;
a3[2] = t3;
cout << a3 << endl;
system("pause");
}
类模板,main函数中试验了三种不同类型,int, char, Teacher类. 踩了很多坑,比如:
1,NULL与“”的区别。在构造函数时,应当对new的空间地址赋值“”,也就是空字符串。而在析构函数时,delete之后应当将地址赋值为NULL,也就是没有地址。
2,复制构造函数与等号运算符重载的问题。复制构造函数是在初始化的时候进行的操作,而等号运算符重载这在对象已经存在的情况下。
3,typename为类时,也需要在类中进行运算符重载。原因??
等等等吧。
代码不亲自敲一遍,还是不行啊。只有踩过的坑多了,才能成长!