Menu
Coddy logo textTech

C++의 접근 제어자

Coddy C++ 여정의 객체 지향 프로그래밍 섹션에 포함된 레슨. 104개 중 34번째.

C++는 누가 클래스 members에 access할 수 있는지를 제어하는 세 가지 access 지정자를 제공합니다: public, protected, private. 이러한 지정자는 캡슐화의 기반을 형성합니다.

class Account {
public:
    std::string ownerName;      // 어디서나 접근 가능
    
protected:
    double interestRate;        // 이 클래스와 파생 클래스에서 접근 가능
    
private:
    double balance;             // 이 클래스 내에서만 접근 가능
};

Public members는 어디에서나 접근할 수 있습니다 - class 내부, derived classes에서, 그리고 외부 코드에서 접근할 수 있습니다. Private members는 가장 제한적이며, class 자체 내부에서만 접근할 수 있습니다. Protected는 그 중간에 해당합니다 - 외부 세계에서는 private처럼 작동하지만, derived classes는 이러한 members에 접근할 수 있습니다.

class Account {
private:
    double balance;
    
public:
    Account() : balance(0) {}
    
    void deposit(double amount) {
        balance += amount;    // OK - 클래스 내부
    }
};

int main() {
    Account acc;
    acc.deposit(100);         // OK - deposit은 public
    // acc.balance = 500;     // ERROR - balance는 private
}

기본적으로 지정자가 주어지지 않으면 class의 모든 members는 private입니다. 이는 무엇을 외부에 공개해야 하는지 명시적으로 결정하도록 유도합니다. 일반적으로 data members는 private으로 만들고, 안전하게 상호 작용할 수 있도록 public methods를 제공합니다.

challenge icon

챌린지

쉬움

접근 지정자가 누가 무엇에 접근할 수 있는지를 어떻게 제어하는지 보여 주는 간단한 직원 관리 시스템을 만들어 보겠습니다. 일부 데이터는 완전히 비공개이고, 일부는 잠재적인 파생 클래스에서 접근할 수 있으며, 일부는 모든 사람에게 공개되는 클래스를 만들 것입니다.

코드를 구성하기 위해 두 개의 파일을 만듭니다:

  • Employee.h: 세 가지 접근 지정자를 모두 사용하여 데이터를 적절하게 보호하는 Employee class를 Define합니다:
    • 공개: 직원의 name(문자열). 어디에서나 access할 수 있습니다
    • 보호됨: 직원의 department(문자열): class 내부와 derived classes에서 access할 수 있지만, 외부에서는 access할 수 없습니다
    • 비공개: 직원의 salary(double): class 자체의 내부에서만 access할 수 있습니다
    • name, department, salary를 받아 세 member를 모두 초기화하는 Constructor
    • private salary 값을 반환하는 public method getSalary()
    • protected department 값을 반환하는 public method getDepartment()
    • 주어진 amount만큼 salary를 증가시키는 public method giveRaise(double amount)(amount가 양수인 경우에만)
    • 직원의 information을 다음 Format으로 출력하는 public method displayInfo(): "Name: <name>, Department: <department>, Salary: $<salary>"
  • main.cpp: Employee object와 상호 작용하여 access 지정자가 어떻게 작동하는지 보여 줍니다. input에서 직원의 이름, department, salary를 읽습니다(각각 별도의 세 줄). 그런 다음:
    • input 값으로 Employee를 Create합니다
    • public member에 directly access하여 직원의 이름을 출력합니다: "Direct access - Name: <name>"
    • getter를 사용하여 department를 출력합니다: "Via getter - Department: <department>"
    • getter를 사용하여 salary를 출력합니다: "Via getter - Salary: $<salary>"
    • 직원에게 5000.0의 급여 인상을 Give합니다
    • "After raise:"를 출력합니다
    • 업데이트된 information을 표시하기 위해 displayInfo()를 Call합니다

<iomanip>std::fixedstd::setprecision(2)를 사용하여 모든 salary 값을 소수점 둘째 자리까지 Format합니다. std::stod()를 사용하여 salary input을 문자열에서 double로 변환합니다.

여기서 중요한 점은 main에서 name에는 directly access할 수 있지만, departmentsalary에는 directly access할 수 없다는 것입니다. public getter methods를 사용해야 합니다. 이것이 바로 캡슐화의 실제 적용입니다. class가 데이터에 access하고 데이터를 수정하는 방식을 제어합니다.

직접 해보기

#include <iostream>
#include <string>
#include <iomanip>
#include "Employee.h"

using namespace std;

int main() {
    // 입력 읽기
    string name;
    string department;
    string salaryStr;
    
    getline(cin, name);
    getline(cin, department);
    getline(cin, salaryStr);
    double salary = stod(salaryStr);
    
    // 급여 출력을 위한 정밀도 설정
    cout << fixed << setprecision(2);
    
    // TODO: 입력 값으로 Employee 객체 생성
    
    // TODO: public 멤버에 직접 접근하여 직원의 이름 출력
    // Format: "Direct access - Name: <name>"
    
    // TODO: getter 메서드를 사용하여 부서 출력
    // Format: "Via getter - Department: <department>"
    
    // TODO: getter 메서드를 사용하여 급여 출력
    // Format: "Via getter - Salary: $<salary>"
    
    // TODO: 직원에게 5000.0의 급여 인상 적용
    
    // TODO: "After raise:" 출력
    
    // TODO: displayInfo()를 호출하여 업데이트된 정보 표시
    
    return 0;
}
quiz icon실력 점검

이 레슨에는 짧은 퀴즈가 포함되어 있습니다. 레슨을 시작해 문제를 풀고 진행 상황을 기록하세요.

객체 지향 프로그래밍의 모든 레슨

직접 연습해 보세요: 온라인 C++ 컴파일러