52 lines
769 B
C++
52 lines
769 B
C++
|
// 深拷贝和浅拷贝
|
||
|
// 浅拷贝举例
|
||
|
#include <iostream>
|
||
|
#include <cstdlib>
|
||
|
#include <cstring>
|
||
|
|
||
|
using namespace std;
|
||
|
|
||
|
class Person
|
||
|
{
|
||
|
private:
|
||
|
char *name;
|
||
|
int age;
|
||
|
|
||
|
public:
|
||
|
Person(const char *name, int age)
|
||
|
{
|
||
|
this->name = (char *)malloc(32);
|
||
|
this->age = age;
|
||
|
}
|
||
|
void release_name_pointer()
|
||
|
{
|
||
|
free(name);
|
||
|
}
|
||
|
|
||
|
public:
|
||
|
void setName(char *name)
|
||
|
{
|
||
|
strcpy(this->name, name);
|
||
|
}
|
||
|
void show()
|
||
|
{
|
||
|
cout << name << ", " << age << endl;
|
||
|
}
|
||
|
};
|
||
|
|
||
|
int main()
|
||
|
{
|
||
|
Person p1("disen", 20);
|
||
|
Person p2 = p1;
|
||
|
Person p3 = Person(p2);
|
||
|
p3.setName("Jack");
|
||
|
|
||
|
p1.show();
|
||
|
p2.show();
|
||
|
p3.show();
|
||
|
|
||
|
// p1.release_name_pointer();
|
||
|
p2.release_name_pointer();
|
||
|
return 0;
|
||
|
}
|