Dotcpp  >  编程教程  >  C++类和对象  >  C++浅拷贝与深拷贝实例详解

# C++浅拷贝与深拷贝实例详解

```/**************************************
//Des：C++教程配套程序
//Author:Huang
//CopyRight：www.dotcpp.com
//Date:2017/8/26
**************************************/
#include<iostream>
#include<Cstring>
using namespace std;
#define PI 3.1415
class Circle
{
private:
double R;
char *str;
public:
Circle(double R,char *str);
~Circle();
double area();
double girth();
};
Circle::~Circle()
{
delete []str;
}
Circle::Circle(double R,char *str)
{
cout<<"Constructor"<<endl;
this->R = R;
this->str = new char[strlen(str)+1];
strcpy(this->str,str);
cout<<this->R<<" "<<this->str<<endl;
}

double Circle::area()
{
return PI*R*R;
}
double Circle::girth()
{

return 2*PI*R;
}
int main()
{

Circle A(5,"NO.1 Old class");
Circle B(A);
return 0;
}```

`This->str = str;`

```#include<iostream>
#include<Cstring>
using namespace std;
#define PI 3.1415
class Circle
{
private:
double R;
char *str;
public:
Circle(double R,char *str);
Circle(Circle &A);
~Circle();
double area();
double girth();
};

Circle::~Circle()
{
delete []str;
cout<<"Call Destructor"<<endl;
}
Circle::Circle(Circle &A)
{
cout<<"Copy Constructor"<<endl;
this->R = A.R;
this->str = new char[strlen(A.str)+1];
strcpy(this->str,A.str);
}
Circle::Circle(double R,char *str)
{
cout<<"Constructor"<<endl;
this->R = R;
this->str = new char[strlen(str)+1];
strcpy(this->str,str);
}

double Circle::area()
{
return PI*R*R;
}
double Circle::girth()
{
return 2*PI*R;
}
int main()
{

Circle A(5,"NO.1 Old class");
Circle B(A);
return 0;
}```

C语言网提供由在职研发工程师或ACM蓝桥杯竞赛优秀选手录制的视频教程，并配有习题和答疑，点击了解：

Dotcpp在线编译　 　　　 （登录可减少运行等待时间）