- 외부에서 접근이 불가 개발자 간의 의사소통의 혼동을 줄임(캡슐화)
- public을 사용하여 접근 허용
- 맴버 함수 매소드를 이용하여 private에 접근 가능
- 맴버 변수는 property라고 칭함
메소드를 이용하여 private 내의 _helath, _power, _name의 값을 변경한다.
#include <iostream>
using namespace std;
class Player {
private:
int _health;
int _power;
string _name;
public:
Player(int health, int power, string name) {
_health = health;
_power = power;
_name = name;
}
void attack(Player& target) {
cout << "Attack " << _name << " -> " << target._name << endl;
target.damaged(_power);
}
void damaged(int power) {
_health -= power;
cout << _name << " damaged " << power << endl;
cout << _name << " helath : " << _health << endl;
if (_health <= 0)
cout << _name << " dead" << endl;
}
};
int main() {
Player garoshi( 200, 100, "Garoshi");
Player thrall( 200, 100, "Thrall");
thrall.attack(garoshi);
thrall.attack(garoshi);
thrall.damaged(100);
return 0;
}
Attack Thrall -> Garoshi
Garoshi damaged 100
Garoshi helath : 100
Attack Thrall -> Garoshi
Garoshi damaged 100
Garoshi helath : 0
Garoshi dead
Thrall damaged 100
Thrall helath : 100