#include<iostream>#include<string.h>classA{public:A(){
std::cout <<"constructor is called"<< std::endl;
n =newint[10];
n[0]=1;}// 默认拷贝构造函数 浅拷贝/*A(const A &t) // 拷贝构造函数的参数一定是引用,否则会出现无限递归
{
std::cout << "copy constructor is called" << std::endl;
n = t.n
}*/// 拷贝构造函数 深拷贝A(const A &t){
std::cout <<"copy constructor is called"<< std::endl;
n =newint[10];memcpy(n, t.n,10);// 通过按字节拷贝,将堆中一块内存存储到另一块内存}// 默认赋值运算符 浅拷贝 /*A &operator=(const A &t) // 形参和返回值一定要是引用类型,否则传参和返回时都会自动调用拷贝构造函数,多两次函数调用,效率低
{
std::cout << "assign constructor is called" << std::endl;
return *this;
if (n != NULL)
{
delete n;
n = NULL;
}
n = t.n;
return *this;
}*/// 深拷贝
A &operator=(const A &t){
std::cout <<"assign constructor is called"<< std::endl;if(this==&t)return*this;if(n !=NULL){delete n;
n =NULL;}
n =newint[10];memcpy(n, t.n,10);//通过按字节拷贝,将堆中一块内存存储到另一块内存return*this;}~A(){
std::cout <<"destructor is called"<< std::endl;delete n;
n =NULL;}voidget(){ std::cout <<"n[0]: "<< n[0]<< std::endl;}private:int*n;};intmain(void){
A a;
A b(a);
A c;
b = a;
b.get();
c.get();return0;}