본문 바로가기

언어/C++

5장 예제- 복사 생성자 오빠 동생 복사 - 얕은 복사

#include <iostream>
#include <cstring>
using namespace std;
/* run this program using the console pauser or add your own getch, system("pause") or input loop */

class Person{
private :
	char *name;
	int id;
public:
	Person(int id, char*name);
	~Person();
	void changeName(char*name);
	void show() {cout << id << ',' << name << endl; }
};


Person :: Person(int id, char*name){
	this->id=id;
	int len=strlen(name);
	this->name =new char [len+1];
	strcpy(this->name , name);
}

Person :: ~Person(){
	if(name){
		delete[] name;
	}
}

void Person :: changeName(char*name){
	if(strlen(name) > strlen(this->name)) {
		return;
	}
	strcpy(this->name, name);
}


int main(){

	Person brother(1,"돌딸기");
	Person sister(brother);
	
	
	cout << "sister객체 생성 직후 ----" << endl;
	
	brother.show();
	sister.show();

	sister.changeName("옥돌이");
	
	cout << "sister의 이름을 옥돌이로 변경한 후 ----" << endl;
	
	brother.show();
	sister.show();
	
	return 0;

}