64,660
社区成员
发帖
与我相关
我的任务
分享
#include <iostream>
using namespace std;
class test
{
private:
int *myInt;
unsigned int len;
public:
test(); //默认的构造函数
~test();//析构函数
test(int* num,unsigned int numLen);//自定义构造函数
test(const test& myTest);//复制构造函数
test& operator=(const test& myTest);
void show();
};
test::test()
{
len = 1;
myInt = new int[len];
myInt[0] = 0;
}
test::~test()
{
delete [] myInt;
myInt = NULL;
}
test::test(int* num,unsigned int numLen)
{
len = numLen;
myInt = new int[len];
for(unsigned int i=0;i<len;++i)//复制
{
myInt[i] = num[i];
}
}
test::test(const test &myTest)
{
len = myTest.len;
myInt = new int[len];
for(unsigned int i=0;i<len;++i)//复制
{
myInt[i] = myTest.myInt[i];
}
}
test& test::operator =(const test &myTest)
{
if(this == &myTest)
return *this; //第一步:检查是否为自赋值
delete [] myInt; //第二步:释放原有内存资源,这一步我感觉
//主要应该是用在释放动态数组的内存,如果myInt不是动态数组
//应该不需要这第二步,直接第三步:*myInt = *myTest.myInt;
len = myTest.len;
myInt = new int[len];
for(unsigned int i=0;i<len;++i) //第三步:复制动态内存的指向的内容
{ //这大概就是所谓的深拷贝,浅拷贝就是直接赋值指针:myInt=myTest.myInt;
myInt[i] = myTest.myInt[i]; //浅拷贝的问题就是,a=b;当b的myInt释放的时候,a的myInt就会指向
} //相同的内存,此内存被b释放,而a却在用,就是所谓野指针了。
return *this; //第四步:返回*this
}
void test::show()
{
cout<<"len= "<<len<<endl;
for(unsigned int i=0;i<len;++i)
{
cout<<myInt[i]<<" ";
}
cout<<endl;
}
int main()
{
const int N = 3;
int t[N] = {1,2,3};
test a;
a.show();
test b(t,N);
test c = b;//注意,这个是初始化,调用的是复制构造函数,而不是=操作符
a = b;//这个是赋值,才是调用=操作符
test d(b);//复制构造函数
a.show();
b.show();
c.show();
d.show();
getchar();
return 0;
}
#include <iostream>
using namespace std;
class CA
{
public:
CA(int b,char* cstr)
{
a=b;
str=new char[b];
strcpy(str,cstr);
}
CA(const CA& C)
{
a=C.a;
str=new char[a]; //深拷贝
if(str!=0)
strcpy(str,C.str);
}
void Show()
{
cout<<str<<endl;
}
~CA()
{
delete str;
}
private:
int a;
char *str;
};
int main()
{
CA A(10,"Hello!");
CA B=A;
B.Show();
return 0;
}