传智扫地僧课程学习笔记。
这里的学习,是为了学习后面的数据结构,
因为后面的数据结构的算法的实现,是以模板的方式实现的,
myvector.h
#include "iostream"
using namespace std;
template <typename T>
class myvector
{
friend ostream& operator<<<T>( ostream &out, const myvector &obj);
public:
myvector( int size=0);
myvector( const myvector &boj);
~myvector();
public:
T& operator[]( int index);
myvector& operator=( const myvector &obj);
public:
int getlen()
{
return m_len;
}
protected:
T *m_space;
int m_len;
private:
};
myvector.cpp
#include "iostream"
using namespace std;
#include "myvector.h"
template <typename T>
ostream& operator<<( ostream &out, const myvector<T> &obj)
{
for( int i=0; i<obj.m_len; i++)
{
out<<obj.m_space[i]<<" ";
}
out<<endl;
return out;
}
template <typename T>
myvector<T>::myvector( int size)
{
m_space = new T[size];
m_len = size;
}
template <typename T>
myvector<T>::myvector( const myvector &obj)
{
m_len = obj.m_len;
m_space = new T[m_len];
for( int i = 0; i<m_len; i++)
{
m_space[i] = obj.m_space[i];
}
}
template <typename T>
myvector<T>::~myvector()
{
if( m_space != NULL )
{
delete []m_space;
m_space = NULL;
m_len = 0;
}
}
template <typename T>
T& myvector<T>::operator[]( int index)
{
return m_space[index];
}
template <typename T>
myvector<T>& myvector<T>::operator=( const myvector<T> &obj)
{
if( m_space != NULL )
{
delete [] space;
m_space = NULL;
m_len = 0;
}
m_len = obj.m_len;
m_space = new T[m_len];
for( int i = 0; i<m_len; i++ )
{
m_space[i] = obj[i];
}
return *this;
}
mainclass.cpp
#include "iostream"
using namespace std;
#include "myvector.cpp"
class Teacher
{
public:
Teacher()
{
age = 33;
strcpy(name, "");
}
Teacher(char *name, int age)
{
this->age = age;
strcpy(this->name, name);
}
void printT()
{
cout << name << ", " << age << endl;
}
private:
int age;
char name[32];
//char *pName2;
};
void main()
{
myvector<int> myv1(10);
for( int i=0; i<myv1.getlen(); i++ )
{
myv1[i] = i+1;
cout<<myv1[i]<<" ";
}
cout<<endl;
myvector<int> myv2 = myv1;
for( int i=0; i<myv2.getlen(); i++)
{
cout<<myv2[i]<<" ";
}
cout<<endl;
cout<<myv2<<endl;
Teacher t1("t1", 31), t2("t2", 32), t3("t3", 33), t4("t4", 34);
myvector<Teacher> tArray(4);
tArray[0] = t1;
tArray[1] = t2;
tArray[2] = t3;
tArray[3] = t4;
for (int i=0; i<4; i++)
{
Teacher tmp = tArray[i];
tmp.printT();
}
cout << tArray;
system("pause");
}
模板类,还是很神奇的,
基础数据类型随便用,
还可以装自己定义的类对象,虽然后面还有需要解决的问题,但是感觉好厉害,
容器本身已经实现了一些操作符的重写,但是这还不够,所存储元素也要实现重写,
你如果不信,举个例子,就去看容器<<操作重写的代码,加入我们的元素是自定义的,
那里的对应代码就是out<<Teacher, 这样写好像不太规范啊,不过要表达的意思是,out不知道怎么去输出你这个类型,所以这也是我们后面学习要掌握的东西,
结论1:如果把Teacher放入到MyVector数组中,并且Teacher类的属性含有指针,就是出现深拷贝和浅拷贝的问题。
结论2:需要Teacher封装的函数有:
1) 重写拷贝构造函数
2) 重载等号操作符
3) 重载左移操作符。
理论提高:所有容器提供的都是值(value)语意,而非引用(reference)语意。容器执行插入元素的操作时,内部实施拷贝动作。所以STL容器内存储的元素必须能够被拷贝(必须提供拷贝构造函数)。