이 게시물에서는 C++에서 private 및 protected 액세스 수정자의 차이점을 이해할 것입니다.
비공개 액세스 수정자
-
'private' 키워드를 사용하여 선언하고 ':'를 붙입니다.
-
수업 외부에서는 액세스할 수 없습니다.
-
'private' 키워드는 클래스 내부의 함수와 속성이 선언된 클래스 멤버만 액세스할 수 있도록 하는 액세스 수정자입니다.
-
멤버 함수 또는 친구 함수만 '비공개'로 표시된 데이터에 액세스할 수 있습니다.
예시
#include <iostream>
using namespace std;
class base_class{
private:
string my_name;
int my_age;
public:
void getName(){
cout << "Enter the name... ";
cin >> my_name;
cout << "Enter the age... ";
cin >> my_age;
}
void printIt(){
cout << "The name is : " << my_name << endl;
cout << "The age is: " << my_age << endl;
}
};
int main(){
cout<<"An object of class is created"<< endl;
base_class my_instance;
my_instance.getName();
my_instance.printIt();
return 0;
} 출력
/tmp/u5NtWSnX5A.o An object of class is created Enter the name... Jane Enter the age... 34 The name is : Jane The age is: 34
보호된 액세스 수정자
-
Protected access modifier는 private access modifier와 유사합니다.
-
'protected' 키워드 뒤에 ':'를 사용하여 선언합니다.
-
'보호됨'으로 선언된 클래스 멤버는 클래스 외부에서 액세스할 수 없습니다.
-
선언된 클래스 내에서 액세스할 수 있습니다.
-
부모 클래스에 '보호된' 멤버가 포함된 파생 클래스에서도 액세스할 수 있습니다.
-
상속 개념으로 작업할 때 사용됩니다.
예시
#include <iostream>
using namespace std;
class base_class{
private:
string my_name;
int my_age;
protected:
int my_salary;
public:
void getName(){
cout << "Enter the name... ";
cin >> my_name;
cout << "Enter the age... ";
cin >> my_age;
}
void printIt(){
cout << "The name is : " << my_name << endl;
cout << "The age is: " << my_age << endl;
}
};
class derived_class : public base_class{
private:
string my_city;
public:
void set_salary(int val){
my_salary = val;
}
void get_data_1(){
getName();
cout << "Enter the city... ";
cin >> my_city;
}
void print_it_1(){
cout << "The salary is: " << my_salary << endl;
printIt();
cout << "The city is: " << my_city << endl;
}
};
int main(){
cout<<"Instance of derived class is being created.."<<endl;
derived_class my_instance_2 ;
my_instance_2.set_salary(100);
my_instance_2.get_data_1();
my_instance_2.print_it_1();
return 0;
} 출력
/tmp/u5NtWSnX5A.o Instance of derived class is being created.. Enter the name... Jane Enter the age... 23 Enter the city... NewYork The salary is: 100 The name is : Jane The age is: 23 The city is: NewYork