ν΄λμ€ λ©€λ²λ€λ static κ°λ μ μ λͺ©ν μ μμ΅λλ€.
νλ‘κ·Έλ¨ λ΄μμ ν ν΄λμ€μ λν΄μ νμ¬ μ‘΄μ¬νλ μ΄ κ°μ²΄μ μλ₯Ό μ»κ³ μΆμλμ κ°μ μν©μμ μ¬μ©ν μ μμ΅λλ€.
int Player::get_num_players() {
return num_players; // num_playersλ Player ν΄λμ€ λ΄μ static μ μ
}
ν€λ νμΌμμ ν΄λμ€λ₯Ό μ μΈνκ³ ,
νΉμ attributeλ₯Ό static ν€μλλ₯Ό λΆμ¬μ μ μΈν©λλ€.
νμ§λ§ μ£Όμν΄μΌ ν μ μ ν΄λΉ μμ±μ λν μ΄κΈ°νλ .cpp νμΌμμ νν©λλ€.
ν΄λμ€μ μ μ λ΄μμ λ°λ‘ μ΄κΈ°νλ₯Ό νλ©΄ μλ©λλ€.
// Static class members
// main.cpp
#include <iostream>
#include "Player.h"
using namespace std;
void display_active_players() {
cout << "Active players: " << Player::get_num_players() << endl;
}
int main() {
display_active_players(); // Active players: 0
Player hero{"Hero"};
display_active_players(); // Active players: 1
{
Player frank{"Frank"};
display_active_players(); // Active players: 2
}
display_active_players(); // Active players: 1
Player *enemy = new Player("Enemy", 100, 100);
display_active_players(); // Active players: 2
delete enemy;
display_active_players(); // Active players: 1
return 0;
}
// Player.cpp
#include "Player.h"
int Player::num_players {0};
Player::Player(std::string name_val, int health_val, int xp_val)
: name{name_val}, health{health_val}, xp{xp_val} {
++num_players;
}
Player::Player(const Player &source)
: Player {source.name, source.health, source.xp} {
}
Player::~Player() {
--num_players;
}
int Player::get_num_players() {
return num_players;
}
// Player.h
#ifndef _PLAYER_H_
#define _PLAYER_H_
#include <string>
class Player
{
private:
static int num_players;
std::string name;
int health;
int xp;
public:
std::string get_name() { return name; }
int get_health() { return health; }
int get_xp() {return xp; }
Player(std::string name_val ="None", int health_val = 0, int xp_val = 0);
// Copy constructor
Player(const Player &source);
// Destructor
~Player();
static int get_num_players();
};
#endif // _PLAYER_H_
'C++ > κ°μ²΄μ§ν₯ νλ‘κ·Έλλ° (OOP)' μΉ΄ν κ³ λ¦¬μ λ€λ₯Έ κΈ
[C++] ν΄λμ€ friend | friends of a Class (0) | 2024.01.02 |
---|---|
[C++] μμ ν΄λμ€ | Using const with Classes (0) | 2024.01.02 |
[C++] this keyword | this ν¬μΈν° (0) | 2024.01.02 |
[C++] Move Constructor | μ΄λ μμ±μ (1) | 2024.01.02 |
[C++] Shallow Copying & Deep Copying | μμ λ³΅μ¬ & κΉμ λ³΅μ¬ (1) | 2023.12.29 |