#include

using namespace std; // 继承 struct Animal{}; struct Dog { Animal an;} class Animal // 基类 { public: void show() { cout << 'age ' << m_age << endl; cout << 'm_pro ' << m_pro << endl; cout << 'm_pri ' << m_pri << endl; } int m_age; protected: int m_pro; private: int m_pri; };

class Dog : public Animal // 继承 子类/派生类 //class Dog : protected Animal // 继承 子类/派生类 //class Dog : private Animal // 继承 子类/派生类 { public: void show() { // 基类方法被覆盖 cout << 'age ' << m_age << endl; cout << 'm_pro ' << m_pro << endl; // cout << 'm_pri ' << m_pri << endl; } };

int main() { cout << sizeof(Dog) << endl; Dog wc; wc.m_age = 10; // wc.m_pro = 10; wc.show(); Animal *ptr = &wc; ptr->show(); return 0; }

解释这个程序的输出内容:程序的输出是: 8 age 10 m_pro 0 age 10 m_pro 0

解释:

  1. sizeof(Dog)输出的是Dog类的大小,根据Animal类的成员变量和继承关系,Dog类的大小为8字节。
  2. 创建了一个Dog对象wc,并设置其m_age为10。
  3. 调用wc的show()方法,输出m_age和m_pro的值。由于m_age和m_pro都是从Animal类继承而来的,而且在Animal类中都是公有的,所以可以直接访问并输出它们的值。
  4. 创建了一个Animal类的指针ptr,并将其指向wc对象。
  5. 通过ptr指针调用show()方法,输出m_age和m_pro的值。由于ptr是指向Animal类的指针,所以只能访问Animal类中的成员变量和方法,无法访问Dog类中的成员变量和方法。因此,输出的值与上一步的输出相同。
C++ 继承示例:Animal 和 Dog 类的大小与访问权限

原文地址: https://www.cveoy.top/t/topic/qrYF 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录