你从访问说明符本章介绍了 C++ 中可用的三个说明符。到目前为止,我们只使用过public
(类的成员可以从类的外部访问)并且private
(成员只能在类内部访问)。第三个说明符,protected
, 类似于private
,但也可以在遗传类:
// 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;
}
亲自试一试 »
截取页面反馈部分,让我们更快修复内容!也可以直接跳过填写反馈内容!