동적할당과 생성자 및 소멸자

2006. 4. 6. 15:32Scrapbook/개발 및 프로그래밍

반응형

명함 정보를 지닐 수 있는 클래스를 정의해 보자. 클래스 이름은 NameCard이고 이름, 전화번호, 주소,직급 정보를 저장할 수 있어야 한다. 생성자 내에서 동적 할당하고, 소멸자에서 할당받은 메모리를 해제하는 형식으로 구현하라.

#include "stdafx.h"
using std::cout;
using std::endl;
using std::cin;

class NameCard{
private:
char* name;
char* phone;
char* address;
char* pos;

public:
NameCard(char* _name, char* _phone, char* _address, char* _pos){
 name=new char[strlen(_name)+1]; //생각이 나지 않았던 부분. new까지는 썼는데...
 strcpy(name,_name); //name=_name; 이라는 생각은 버리자.

 phone=new char[strlen(_phone)+1];
 strcpy(phone,_phone);

 address=new char[strlen(_address)+1];
 strcpy(address,_address);

 pos=new char[strlen(_pos)+1];
 strcpy(pos,_pos);
}

void ShowDate();

~NameCard(){
 delete []name;  //delete를 다 빼먹고 코딩. 이래서야 힙 메모리가 해지가 될란가.ㅋ
 delete []phone;
delete []address;
 delete []pos;
}
};

void NameCard::ShowDate(){
cout<<"이  름: "<<name<<endl;
cout<<"전화번호: "<<phone<<endl;
cout<<"주    소: "<<address<<endl;
cout<<"직  급: "<<pos<<endl;
}

int main(void)
{
NameCard Lee("Shin Dong Yoon", "02-868-6300","
www.couplestyle.com","manager");
Lee.ShowDate();
return 0;
}

소멸자 까지 완료했다.이제 클래스의 배열도 들어갈 차례.
반응형