객체지향의 4가지 특성
- 캡슐화: 데이터와 데이터를 처리하는 함수를 하나로 묶음
- 다형성: 같은 자료형에 여러 가지 타입의 데이터를 대입하여 다양한 결과를 얻어낼 수 있는 성질
- 상속: 부모 클래스에 정의된 변수 및 메서드를 자식 클래스에서 상속받아 사용하는 것
- 추상화: 객체의 공통적 속성과 기능을 추출하여 정의
캡슐화의 목적
- 멤버 변수에 대한 보호
- 중요한 멤버는 다른 클래스, 객체에서 접근 불가하도록 보호
- 외부 인터페이스를 위해 일부는 접근 허용
생성자와 소멸자
1. 생성자
- 객체가 생성될 때 자동으로 호출되는 함수
2. 소멸자
- 객체가 소멸될 때 자동으로 호출되는 함수
- 동적 메모리를 할당 한 경우 소멸자에서 해제 해야 한다
생성자는 별도로 정의하지 않으면 컴파일러에서 기본 생성자를 사용한다
접근 제어
- private, public, protected 의 종류가 있음
- 디폴트 접근 지정은 private
public
- 모든 클래스에서 접근 가능
private
- 해당 클래스에서 접근 가능
- 멤버 변수는 일반적으로 private 로 선
protected
- 해당 클래스 및 상속된 클래스에서 접근 가능
getter 와 setter(접근자와 설정자)
- 멤버 변수의 접근을 제한
- 접근자는 보통 get, 설정자는 보통 set
자유실습
포켓몬의 정보를 저장할수 있는 클래스를 정의 한 후 입력 값을 설정자 함수를 통해 값을 저장
접근자 함수를 통해 저장된 값을 불러와 출력
#include <stdio.h>
#include <iostream>
#include <string>
using namespace std;
class Pokemon
{
private:
// 멤버 변수 정의
string name;
int level;
string type;
string item;
public:
// 생성자와 소멸자
Pokemon() { name = "", level = 1, type = "노말", item = ""; }
~Pokemon() {};
// 멤버 함수 정의 (설정자와 접근자)
int getLevel()
{
return level;
}
void setLevel(int lev)
{
level = lev;
}
string getName()
{
return name;
}
void setName(string nm)
{
name = nm;
}
string getType()
{
return type;
}
void setType(string tp)
{
type = tp;
}
string getItem()
{
return item;
}
void setItem(string item)
{
this->item = item;
}
};
int main()
{
int n;
cout << "등록할 포켓몬의 수: ";
cin >> n;
Pokemon* pk = new Pokemon[n];
for (int i = 0; i < n; i++)
{
string new_name;
int new_level;
string new_type;
string new_item;
cout << "이름: ";
cin >> new_name;
cout << "레벨: ";
cin >> new_level;
cout << "타입: ";
cin >> new_type;
cout << "지닌물건: ";
cin >> new_item;
pk[i].setName(new_name);
pk[i].setLevel(new_level);
pk[i].setType(new_type);
pk[i].setItem(new_item);
}
cout << "====== 포켓몬 목록 ======" << "\n";
for (int i = 0; i < n; i++)
{
string curr_name = pk[i].getName();
int curr_level = pk[i].getLevel();
string curr_type = pk[i].getType();
string curr_item = pk[i].getItem();
cout << "이름: ";
cout << curr_name;
cout << "/ 레벨: ";
cout << curr_level;
cout << "/ 타입: ";
cout << curr_type;
cout << "/ 지닌물건: ";
cout << curr_item << "\n";
}
delete[] pk;
}
실행 결과

