案例: class Student{ public: char * p_mname; int mage; Student(char * name, int age){ p_mname = new char[strlen(name)+1]; strcpy(p_mname, name); mage = age; } ~Student(){ if(p_mnae! = null){ delete[] p_mname; p_mname = null; mage = 0; } } prinT(){ cout<<p_mname<<" : " << mage<,endl; }
// Student st2 = st1; //解决浅拷贝问题,重写拷贝构造函数 Student( const Student & obj){ p_mname = new char[strlen(obj.p_mname)+1]; strcpy(p_mname, obj.p_mname); mage = obj.mage; } // st3 = st2 = st1 返回值必须是引用 //重载 = 操作符 Student& operator=(const Student & obj){ //先把st2的旧内存释放掉 if(p_mname! = null){ delete[] p_mname; p_mname = null; mage = 0; } //根据st1的大小分配内存 p_mname = new char[strlen(obj.p_mname)+1]; //copy st1的数据 strcpy(p_mname, obj.p_mname); mage = obj.mage;
return *this; } };
void main(){ Student st1("zhang min", 32); vector<Student> v1; v1.push_back(st1); //此处会报错 深拷贝和浅拷贝的问题 C++默认的拷贝函数是浅拷贝, 解决方法见深色部分 }
各种容器的使用时机:

