숏컷 코드
cpp
class Counter {
public:
Counter() { ++total_; }
~Counter() { --total_; }
int id() const { return id_; }
static int total() { return total_; } // 인스턴스 없이 호출
private:
int id_ = ++next_id_;
static int total_; // 모든 인스턴스가 공유
static int next_id_;
};
int Counter::total_ = 0; // .cpp에서 정의 필수
int Counter::next_id_ = 0;문법
public / protected / private
세 접근 제어자는 누가 접근할 수 있는가를 정의합니다.
cpp
class Base {
public:
int pub = 1; // 어디서나 접근 가능
protected:
int prot = 2; // 자신 + 파생 클래스만
private:
int priv = 3; // 자신 클래스만
};
class Derived : public Base {
void f() {
pub = 10; // ✅ public
prot = 20; // ✅ protected — 파생 클래스 접근 가능
// priv = 30; // ❌ private — 접근 불가
}
};
Base b;
b.pub = 10; // ✅
// b.prot = 20; // ❌ 외부에서 protected 접근 불가static 멤버 — 클래스에 속하는 공유 데이터
static 멤버 변수는 인스턴스와 무관하게 클래스 전체에서 하나만 존재합니다. 모든 인스턴스가 같은 값을 공유합니다. 선언은 클래스 안에, 정의(메모리 할당)는 .cpp에서 해야 합니다.
cpp
class Logger {
public:
static int log_count; // 선언만
};
int Logger::log_count = 0; // .cpp에서 정의 (메모리 할당)
Logger a, b;
Logger::log_count = 5; // a, b 모두에 반영됨static 멤버 함수 — this 없는 함수
static 멤버 함수는 this가 없으므로 인스턴스 없이 호출할 수 있지만, 인스턴스 멤버에 접근할 수 없습니다. static 멤버와 전달받은 인자만 사용합니다.
cpp
class Config {
public:
static Config& instance() {
static Config inst; // 프로그램 생애주기 동안 하나만 생성
return inst;
}
// static 함수에서 인스턴스 멤버 접근 불가
// int get() { return value_; } // ✅ 비static 함수만 가능
private:
Config() = default;
int value_ = 0;
};체크포인트
| 접근 제어 | 자신 | 파생 클래스 | 외부 |
|---|---|---|---|
public | ✅ | ✅ | ✅ |
protected | ✅ | ✅ | ❌ |
private | ✅ | ❌ | ❌ |
| 상황 | 적합한 선택 |
|---|---|
| 클래스 전체 공유 카운터/플래그 | static 멤버 변수 |
| 인스턴스 없이 유틸리티 함수 | static 멤버 함수 |
| 파생 클래스에서 접근할 내부 데이터 | protected |
| 외부에 노출하지 않을 구현 | private |
주의할 점
static 멤버 변수는 클래스 안에서 선언만 하고 .cpp에서 정의해야 합니다. 헤더에서 정의하면 링크 오류(multiple definition)가 납니다.
cpp
// ❌ 헤더에서 static 멤버 정의
// counter.h
class Counter {
static int count_ = 0; // C++11 이전 — 링크 오류 가능
};
// ✅ 헤더에서 선언, .cpp에서 정의
// counter.h
class Counter {
static int count_; // 선언만
};
// counter.cpp
int Counter::count_ = 0; // 정의 (메모리 할당)
// ✅ C++17: inline static으로 헤더에서 정의 가능
class Counter2 {
inline static int count_ = 0; // 헤더에서 정의 가능
};참고 링크
1 sources