C++ protected 關鍵字
示例
使用 protected
關鍵字使屬性可被派生類訪問
// Base class
class Employee {
protected: // Protected access specifier
int salary;
};
// Derived class
class Programmer: public Employee {
public:
int bonus;
void setSalary(int s) {
salary = s;
}
int getSalary() {
return salary;
}
};
int main() {
Programmer myObj;
myObj.setSalary(50000);
myObj.bonus = 15000;
cout << "Salary: " << myObj.getSalary() << "\n";
cout << "Bonus: " << myObj.bonus << "\n";
return 0;
}
定義和用法
protected
關鍵字是一個訪問修飾符,用於宣告受保護的屬性和方法,這意味著它們只能被類內的其他方法或其派生類的方法訪問。
相關頁面
有關訪問修飾符的更多資訊,請參閱我們的 C++ 訪問修飾符教程。
有關派生類的更多資訊,請參閱我們的 C++ 繼承教程。