[C++] Class

스윗포테이토·2022년 10월 29일
1

오늘은 가볍게 C++ 클래스에 대해 정리해보려고 한다.

우선 클래스를 선언하는 기본 문법이다.

class Person{};

주의할 점은 뒤에 세미콜론이 있다는 것이다...!
지금은 비어있지만, 괄호 안에 멤버 함수, 변수 등을 선언하기 때문에 내용이 길어져서 세미콜론을 깜빡하는 경우가 있다.

멤버 변수와 멤버 함수는 private 영역과 public 영역으로 나뉘는데, private은 직접 접근이 불가능하다.
따라서 private 변수를 참조하거나 수정하기 위해서는 멤버 함수를 거쳐야 한다.

//	ex
class Person{
private:
	string secret;
public:
	string getSecret(){
    	return this->secret;
    }
    void updateSecret(string new_secret){
    	this->secret = new_secret;
    }
};

멤버 변수 초기화

초기화의 경우 일반적으로 생성자를 통해 진행하며, 이 생성자는 여러개 정의할 수 있다. 다만 매개변수의 종류가 달라야 한다.

// 클래스 선언
class Person{
private:
	string name;
	int age;
public:
	Person(string name){
    	this->name = name;
        this->age = 0;
    }
	Person(int age){
    	this->age = age;
        this->name = "unknown";
    }
    Person(string name, int age){
    	this->name = name;
        this->age = age;
    }
};

// 객체 선언(생성) 및 초기화
Person p1 = Person(20);
Person p2 = Person("goguma");
Person p3 = Person("gamja", 30);

소멸자

소멸자는 말 그대로 객체를 소멸시키는 역할을 한다. 즉, 메모리 공간에서 지운다고 생각하면 된다.

class Person{
public:
	~Person(){
    	cout << this->name << " deleted\n";
    }
};

소멸자는 하나만 선언이 가능하다.

필요하지 않다면 생성자와 소멸자는 직접 정의하지 않아도 된다. 직접 정의하지 않는 경우 컴파일 과정에서 기본 생성자와 소멸자가 만들어지기 때문이다.

리팩토링

클래스를 생성하면서 모든 멤버 함수 및 변수를 한번에 정의할 수 있지만, 내용이 너무 많으면 찾아보기 어려워진다. 따라서 나는 주로 클래스 내부에는 멤버 함수를 선언하고, 정의는 따로 해주는 편이다.

class Person{
private:
	string name, secret;
	int age;
public:
	// 생성자
    Person(string name);
	Person(int age;
    Person(string name, int age);
    
    
	string getSecret();
    void updateSecret(string new_secret);
    
    // 소멸자 - 간단한건 내부에 선언
    ~Person(){
    	cout << this->name << " deleted\n";
    }
};

// 멤버 함수 정의

Person::Person(string name){
    this->name = name;
    this->age = 0;
}
Person::Person(int age){
    this->age = age;
    this->name = "unknown";
}
Person::Person(string name, int age){
    this->name = name;
    this->age = age;
}
string Person::getSecret(){
    return this->secret;
}
void Person::updateSecret(string new_secret){
    this->secret = new_secret;
}    

소스코드가 많이 복잡해질 경우, class 선언부는 헤더파일에 넣어 분리하는 것도 좋은 방법인 듯 하다.

profile
나의 삽질이 미래의 누군가를 구할 수 있다면...

0개의 댓글