公有继承 public:
当类的继承方式为公有继承时, 基类的公有和保护成员的访问属性在派生类中 不变, 而基类的私有成员不可访问. 即基类的公有成员和保护成员被继承到派生类中仍作为派生类的公有成员和保护成员. 派生类的其他成员可以直接访问它们. 无 论派生类的成员还是派生类的对象都无法访问基类的私有成员.
公有继承: 当公有继承时, 基类的公有变成派生类的公有, 保护变成派生类的保护, 私有不可以直接被派生类访问, 可通过公有和保护间接访问!
- #include <iostream>
- using namespace std;
- class info {
- public:
- int getter(void) {
- return age;
- }
- void setter(int a) {
- age = a;
- }
- void pri(void) {
- cout << age << endl;
- }
- protected:
- int prot;
- private: // 派生类不可访问
- int age;
- };
- class info_j :public info {
- public:
- void info_pri(void) {
- cout << num << endl;
- }
- void set_pri_prot(int a) {
- info::prot = a;
- cout << info::prot << endl;
- }
- private:
- int num;
- };
- int main(void) {
- info_j infoj; // 定义一个派生类
- infoj.setter(666); // 派生类直接访问基类的 public
- infoj.pri();
- infoj.set_pri_prot(777); // 派生类直接访问基类的 protected
- system("pause");
- return 0;
- }
笔记
来源: http://www.bubuko.com/infodetail-3158947.html