정수와 정수배열의 정적 메모리할당;
문자열의 크기를 컴파일 타임에서 정의한 경우; 메모리 사용이 비효율적임.
#include<iostream> #include<cstring> using std::cout; using std::endl; using std::cin; const int SIZE=20; class Person { char name[SIZE]; char phone[SIZE]; int age; public: Person(char* _name, char* _phone, int _age); void ShowData(); }; Person::Person(char* _name, char* _phone, int _age) { strcpy(name, _name); strcpy(phone, _phone); age=_age; } void Person::ShowData() { cout<<"name: "<<name<<endl; cout<<"phone: "<<phone<<endl; cout<<"age: "<<age<<endl; } int main() { Person p("KIM", "013-123-1234", 30); p.ShowData(); return 0; } |
정수와 정수배열의 동적 메모리할당;
입렵받는 문자열의 크기는 런타임에서 결정됨. 따라서 동적 메모리 할당으로 메모리를 효율적으로 사용함.
#include<iostream> #include <cstring> using namespace std; class Person { char *name; char *phone; int age; public: Person(char *_name, char *_phone, int _age); void ShowData(); }; Person::Person(char *_name, char *_phone, int _age) { name=new char[strlen(_name)+1]; //name 생성자 strcpy(name, _name); phone=new char[strlen(_phone)+1]; //phone 생성자 strcpy(phone, _phone); age=_age; } void Person::ShowData() { cout<<"name: "<<name<<endl; cout<<"phone: "<<phone<<endl; cout<<"age: "<<age<<endl; } int main() { Person p("KIM", "013-333-5555", 22); p.ShowData(); return 0; } |
위 코드는 '메모리 누수'현성이 존재함. 즉, 런타임에서 배정한 메모리 영역은 제거하기 전까지는 사용할 수 없음. 따라서, 동적 메모리할당을 한 뒤에는 반드시 재거해야됨.
수동 소멸자
#include<iostream> #include <cstring> using namespace std; class Person { char *name; char *phone; int age; public: Person(char* _name, char* _phone, int _age); void ShowData(); void DelMemory(); }; Person::Person(char* _name, char* _phone, int _age) { name=new char[strlen(_name)+1]; strcpy(name, _name); phone=new char[strlen(_phone)+1]; strcpy(phone, _phone); age=_age; } void Person::ShowData() { cout<<"name: "<<name<<endl; cout<<"phone: "<<phone<<endl; cout<<"age: "<<age<<endl; } void Person::DelMemory() { delete []name; delete []phone; } int main() { Person p("KIM", "013-333-5555", 22); p.ShowData(); p.DelMemory(); return 0; } |
자동 소멸자
동적할당된 메모리 영역은 생성 후 자동으로('~'가 포함된 간단한 명령어를 사용) 소멸시켜야한다.
#include<iostream> #include <cstring> using std::cout; using std::endl; class Person { char *name; char *phone; int age; public: Person(char* _name, char* _phone, int _age); ~Person(); void ShowData(); }; Person::Person(char* _name, char* _phone, int _age) { name=new char[strlen(_name)+1]; strcpy(name, _name); phone=new char[strlen(_phone)+1]; strcpy(phone, _phone); age=_age; } Person::~Person() { delete []name; delete []phone; } void Person::ShowData() { cout<<"name: "<<name<<endl; cout<<"phone: "<<phone<<endl; cout<<"age: "<<age<<endl; } int main() { Person p("KIM", "013-333-5555", 22); p.ShowData(); return 0; } |
'C++Language' 카테고리의 다른 글
C++언어(16); 복사 생성자 (0) | 2018.01.22 |
---|---|
C++언어(14); 클래스; 객체의 동적 메모리 할당 (0) | 2018.01.21 |
C++언어(11); 캡슐화; 클래스의 정보은닉 (0) | 2018.01.20 |
C++언어(10); 클래스; 기본멤버 함수 (0) | 2018.01.19 |
C++언어(9); 구조체 (0) | 2018.01.19 |