您的位置:首页 > 其它

第六周项目:深复制体验

2015-04-19 10:34 211 查看
代码:

#include<iostream>
#include<cstring>
using namespace std;
class A
{
private:
char *a;
public:
A(char *aa)
{
a = new char[strlen(aa)+1];
strcpy(a, aa);
}
~A()
{
delete []a;
}
void output()
{
cout<<a<<endl;
}
};
int main(){
A a("good morning, code monkeys!");
a.output();
A b("good afternoon, codes!");
b.output();
return 0;
}


运行结果:



为类A增加复制构造函数

代码:

#include<iostream>
#include<cstring>
using namespace std;
class A
{
private:
char *a;
public:
A(char *aa)
{
a = new char[strlen(aa)+1];
strcpy(a,aa);
}
~A()
{
delete []a;
}
A(A &b)
{
a = new char[strlen(b.a)+1];
strcpy(a,b.a);
}
void output()
{
cout<<a<<endl;
}
};
int main()
{
A a("good morning,code monkeys!");
a.output();
A b(a);
b.output();
return 0;
}


运行结果:

内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: