Programming Languages/C++

캡슐화와 접근 지정자

newclass 2025. 3. 28. 00:00

5.2 캡슐화와 접근 지정자

5.2.1 캡슐화(Encapsulation)

캡슐화는 데이터와 이를 처리하는 함수를 하나의 단위로 묶고, 외부에서의 접근을 제한하는 OOP의 핵심 원칙입니다. 이를 통해 데이터 무결성을 보호하고 구현 세부 사항을 숨길 수 있습니다.

5.2.2 접근 지정자(Access Specifiers)

C++에서는 세 가지 접근 지정자를 통해 캡슐화 수준을 제어합니다:

  1. public: 어디서든 접근 가능
  2. private: 해당 클래스 내부에서만 접근 가능
  3. protected: 해당 클래스와 파생 클래스에서 접근 가능
#include <iostream>
#include <string>

class BankAccount {
private:
    // 클래스 내부에서만 접근 가능한 데이터
    std::string accountNumber;
    double balance;
    
public:
    // 외부에서 접근 가능한 인터페이스
    void setAccountNumber(const std::string& accNum) {
        accountNumber = accNum;
    }
    
    std::string getAccountNumber() const {
        return accountNumber;
    }
    
    void deposit(double amount) {
        if (amount > 0) {
            balance += amount;
            std::cout << amount << "원이 입금되었습니다." << std::endl;
        } else {
            std::cout << "유효하지 않은 금액입니다." << std::endl;
        }
    }
    
    bool withdraw(double amount) {
        if (amount > 0 && balance >= amount) {
            balance -= amount;
            std::cout << amount << "원이 출금되었습니다." << std::endl;
            return true;
        } else {
            std::cout << "출금할 수 없습니다. 잔액이 부족하거나 유효하지 않은 금액입니다." << std::endl;
            return false;
        }
    }
    
    double getBalance() const {
        return balance;
    }
    
protected:
    // 파생 클래스에서도 접근 가능한 데이터/함수
    void applyServiceCharge(double charge) {
        balance -= charge;
    }
};

int main() {
    BankAccount account;
    
    account.setAccountNumber("123-456-789");
    account.deposit(10000);
    account.withdraw(3000);
    
    std::cout << "계좌번호: " << account.getAccountNumber() << std::endl;
    std::cout << "현재 잔액: " << account.getBalance() << "원" << std::endl;
    
    // 아래 코드는 컴파일 오류 발생
    // account.balance = 1000000;  // private 멤버 직접 접근 불가
    // account.applyServiceCharge(100);  // protected 멤버 접근 불가
    
    return 0;
}

5.2.3 Getter와 Setter 메서드

캡슐화된 데이터에 안전하게 접근하고 수정하기 위해 일반적으로 getter와 setter 메서드를 사용합니다:

class Rectangle {
private:
    double width;
    double height;
    
public:
    // Getter 메서드
    double getWidth() const {
        return width;
    }
    
    double getHeight() const {
        return height;
    }
    
    // Setter 메서드 (유효성 검사 포함)
    void setWidth(double w) {
        if (w > 0) {
            width = w;
        } else {
            std::cout << "너비는 양수여야 합니다." << std::endl;
        }
    }
    
    void setHeight(double h) {
        if (h > 0) {
            height = h;
        } else {
            std::cout << "높이는 양수여야 합니다." << std::endl;
        }
    }
    
    // 면적 계산 메서드
    double getArea() const {
        return width * height;
    }
};