// R.cpp : Defines the entry point for the console application. // #include "stdafx.h" #include <string> #include <iostream> using namespace std; class A { public: A() { } A(A &a);//重载拷贝函数 A(int id,char* t_name) { _id =id; name = new char[strlen(t_name)+1]; strcpy(name,t_name); } ~A() { delete name; name = NULL; } char* name; A& operator =(A& a) //注意:此处一定要返回对象的引用,否则返回后其值立即消失! { // if(name!=NULL) // delete name; name = NULL; int si = strlen(a.name); char* temp = new char[si+1]; this->_id=a._id; int len=strlen(a.name); // name=new char[len+1]; //strcpy(name,a.name); strcpy(temp,a.name); if (name!=NULL) { delete[] name; } name = temp; return *this; } protected: private: int _id; }; A::A(A &a) { _id=a._id; name=new char[strlen(a. name)+1];//也是构造函数,需要申请空间 if( name!=NULL) strcpy( name,a. name); } int main(int argc, char* argv[]) { A a(1,"james"); //A b = a;//b 还没有存在对象,所以是拷贝构造函数,如果存在了,就是赋值函数 A b; b = a; cout<<b.name<<endl; cout<<a.name<<endl; strcpy(a.name,"a"); cout<<b.name<<endl; cout<<a.name<<endl; cout<<&(b.name)<<endl; cout<<&(a.name)<<endl; return 0; }
注意在=重载中,delete量前的赋值
本文介绍了一个C++示例程序,详细展示了类的拷贝构造函数及赋值运算符重载的实现方式。通过具体的代码示例解释了如何正确地进行深拷贝,避免了浅拷贝带来的问题。
1946

被折叠的 条评论
为什么被折叠?



