C++ 访问继承
访问修饰符
从访问修饰符中学习到C++中有三个修饰符。到目前为止,我们只使用public
(类的成员可以从类外部访问)和private
(成员只能在类内部访问)。第三个修饰符protected
类似于private
,但也可以在继承的类中访问它:
实例
// 基类
class
Employee {
protected: // 受保护的访问修饰符
int salary;
};
// 派生类
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;
}
运行实例 »