/*******************************************************
*author:彭晓林
*copyright: 版权所有,翻版不究
*function: 构造函数深层复制示例
******************************************************/
#include <iostream>
#include <string>
using namespace std;
class DEMO
{
public:
DEMO(int a)
{
int* temp = new int;
x = temp;
*x = a;
}
void set(int a)
{
*x = a;
}
DEMO(DEMO &demo)
{
int* a = new int;
*a = *(demo.x);
*x = *a;
}
void print();
private:
int* x;
};
void DEMO::print()
{
cout<<"x = "<<*x<<endl;
cout<<"x address :"<<x<<endl;
}
int main()
{
DEMO* TestA = new DEMO(1);
TestA->print();
DEMO TestB(*TestA);
TestB.print();
TestB.set(32);
TestA->print();
TestB.print();
while(1);
}
本文通过一个C++示例介绍了如何实现类的深拷贝。示例中定义了一个包含指向整数指针成员变量的DEMO类,并通过构造函数实现深拷贝。文章展示了在修改拷贝对象的值后,原始对象不受影响的情况。
1万+

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



