1. 程式人生 > >C++類模板練習

C++類模板練習

練習編寫了一個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為類時,也需要在類中進行運算子過載。原因??

等等等吧。

程式碼不親自敲一遍,還是不行啊。只有踩過的坑多了,才能成長!