Notice
Recent Posts
Recent Comments
Link
일 | 월 | 화 | 수 | 목 | 금 | 토 |
---|---|---|---|---|---|---|
1 | 2 | 3 | 4 | 5 | ||
6 | 7 | 8 | 9 | 10 | 11 | 12 |
13 | 14 | 15 | 16 | 17 | 18 | 19 |
20 | 21 | 22 | 23 | 24 | 25 | 26 |
27 | 28 | 29 | 30 |
Tags
- 반복문
- Python
- Class
- 배열
- 함수
- 티스토리챌린지
- pointer
- Pre-processing
- function
- pass by reference
- 파이썬
- 오블완
- array
- baekjoon
- programming
- 포인터
- Object Oriented Programming
- 백준
- raw data
- assignment operator
- Deep Learning
- OOP
- C++
- predictive analysis
- 문자열
- Data Science
- const
- 알고리즘
- string
- vscode
Archives
- Today
- Total
Channi Studies
[C++] 스태틱 클래스 멤버 | Static Class Members 본문
클래스 멤버들도 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 |