Student(int _number, string _name, string _adress)
: number(_number), name(_name), adress(_adress)
{
}
...
int main(){
Student* std3 = new Student(1111, "김민지", "서울");
동적할당(new)을 하면 const/참조형 멤버변수를 사용가능하다.
동적할당된 공간은 포인터로 접근해야한다.
멤버함수를 가리킬때는 ->
을 사용한다.
ex ) std3->print();
동적할당을 하면 반드시 해제(delete)를 해줘야한다.
메모리절약을 위해서다.
int main(){
Student* std3 = new Student(1111, "김민지", "서울");
delete std3;
Student* std4 = new Student[2];
for(int i = 0; i<2; i++){
std4[i].print();
}
delete[] std4;
배열요소에 해당하는 객체멤버에 포인터를 사용할 때는 ->
를 사용할 수 없다. .
으로 접근해야한다.
#include <iostream>
#include <string.h>
using namespace std;
class MString {
public :
MString(const char* str) {
unsigned int l = strlen(str);
c_str_ = new char[l+1]; //'\0'(널문자)가 들어갈 공간 +1
strcpy(c_str_, str);
}
char* c_str(void) {
return c_str_; //_(언더 스코어) 멤버변수라는 뜻
}
private:
char* c_str_; //문자열의 시작주소
};
int main() {
MString* str = new MString("I will be back");
cout << str->c_str() << endl;
return 0;
}
I will be back
strlen
으로 길이를 l
에 저장하고
c_str_
이라는 char배열을 만든다.
strcpy
로 str
의 값을 c_str_
로 복사한다.
str
이 c_str
을 가리켜 호출하고 변수 c_str_
을 리턴해 메인에서 출력하게 한다.
~
기호는 소멸자를 나타낸다.
소멸자로 생성자에서 동적할당한 메모리를 메모리 누수 방지를 위해 해제해준다. 소멸자를 쓰면 객체만 삭제될 뿐 동적할당으로 생성된 문자열은 남아있다.
class MString {
public :
~MString() {
delete[] c_str_;
}
};