您的位置:首页 > 其它

类模板的练习:数组类模板

2018-03-23 15:25 267 查看
Array.h#ifndef __ARRAY_H__
#define __ARRAY_H__

#include <iostream>
using namespace std;

template <typename T>
class Array
{
//重载输出数组 的<< 运算符
friend ostream& operator<<(ostream &out, Array &a)
{
for (int i = 0; i < a.len; i++)
out << a[i] << " ";
return out;
}
public:
Array(int len = 0)//构造
{
if (len <= 0)
{
this->len = 0;
m_p = NULL;
return;
}
this->len = len;
m_p = new T[len];
}

Array(const Array &a)//拷贝构造
{
if (a.len <= 0)
{
this->len = 0;
m_p = NULL;
return;
}
this->len = a.len;
m_p = new T[a.len];
for (int i = 0; i < len; i++)
m_p[i] = a.m_p[i];
}

~Array()//析构
{
if (m_p != NULL)
delete[] m_p;
m_p = NULL;
len = 0;
}

Array& operator=(const Array &a)//赋值重载
{
if (this != &a)
{
Array tmp = a;//开辟临时空间,调用拷贝构造复制a的值,如果开辟失败,不会往下执行,避免内部变量找不到原来的指向

T *p = tmp.m_p;//开辟正常的情况下,一tmp为中转站交换a.m_p和this->m_p的指向
tmp.m_p = m_p;//tmp_mp指向原先this_mp的指向,函数运行完后,编译器自动回收栈上空间
m_p = p; //避免内存泄漏

len = a.len;//复制其余数据
}

return *this;
}

T& operator[](int index)// 数组下标重载
{
return m_p[index];
}
private:
int len;//数组长
T *m_p;//数组指针
};

#endif //__ARRAY_H__Array.cpp#include <iostream>
#include "Array.h"
using namespace std;

int main1()
{
Array<int> a(10);
for (int i = 0; i < 10; i++)
a[i] = i;
cout << a << endl;

Array<int> b = a;
cout << b << endl;

Array<int> c;
c = a;
cout << c << endl;

Array<double> d(10);
for (int i = 0; i < 10; i++)
d[i] = 100.0/(i+1);
cout << d << endl;

return 0;
}

//类 的数组
class Student
{
friend ostream& operator<< (ostream& out, Student &s);
public:
Student(){}
Student(int id, char *name)
{
this->id = id;
this->name = name;
}
private:
int id;
char *name;
};

//重载输出类的 <<运算符
ostream& operator<< (ostream& out, Student &s)
{
out << "id = " << s.id << ", name = " << s.name << endl;
return out;
}

int main2()
{
//a是一个数组,里面放的是5个类
Student a[5] = {
Student(1, "小明1"),
Student(2, "小明2"),
Student(3, "小明3"),
Student(4, "小明4"),
Student(5, "小明5")
};
Array<Student> s(5);

//数组中存的是值,往数组里存数据是值的复制
//会调用赋值运算符重载函数
for (int i = 0; i < 5; i++)
{
s[i] = a[i];
}
cout << s << endl;
return 0;
}

int main()
{
Student *ps1 = new Student(1, "小明1");
Student *ps2 = new Student(2, "小明2");
Student *ps3 = new Student(3, "小明3");
Student *ps4 = new Student(4, "小明4");
Student *ps5 = new Student(5, "小明5");

Array<Student*> s(5);
s[0] = ps1;
s[1] = ps2;
s[2] = ps3;
s[3] = ps4;
s[4] = ps5;

for (int i = 0; i < 5; i++)
cout << *s[i] << endl;

return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: