#include#include using namespace std; //基类A class A{ public: A(int a, int b); public: void display(); public: int m_a; int m_b; }; A::A(int a, int b): m_a(a), m_b(b){} void A::display(){ printf("m_a=%d, m_b=%dn", m_a, m_b); } //派生类B class B: public A{ public: B(int a, int b, int c); void display(); public: int m_c; }; B::B(int a, int b, int c): A(a, b), m_c(c){ } void B::display(){ printf("m_a=%d, m_b=%d, m_c=%dn", m_a, m_b, m_c); } //声明并定义派生类C class C: public B{ public: C(char a, int b, int c, int d); public: void display(); public: int m_b; //遮蔽A类的成员变量 int m_c; //遮蔽B类的成员变量 int m_d; //新增成员变量 }; C::C(char a, int b, int c, int d): B(a, b, c), m_b(b), m_c(c), m_d(d){ } void C::display(){ printf("A::m_a=%d, A::m_b=%d, B::m_c=%dn", m_a, A::m_b, B::m_c); printf("C::m_b=%d, C::m_c=%d, C::m_d=%dn", m_b, m_c, m_d); } int main(){ A obj_a(99, 10); B obj_b(84, 23, 95); cout<<"&obj_a.m_a="<<&obj_a.m_a<<" &obj_a.m_b="<<&obj_a.m_b<<" &obj_a="<<&obj_a< &obj_a.m_a=0x7fffc1edf9dc &obj_a.m_b=0x7fffc1edf9e0 &obj_a=0x7fffc1edf9dc &obj_b.m_a=0x7fffc1edf9e4 &obj_b.m_b=0x7fffc1edf9e8 &obj_b.m_c=0x7fffc1edf9ec &obj_b=0x7fffc1edf9e4 m_a=99, m_b=10 A::m_a=84, A::m_b=23, B::m_c=95 C::m_b=23, C::m_c=95, C::m_d=60 &obj_c.m_a=0x7fffc1edf9f0 &obj_c.A::m_b=0x7fffc1edf9f4 &obj_c.B::m_c=0x7fffc1edf9f8 &obj_c.m_b=0x7fffc1edf9fc &obj_c.m_c=0x7fffc1edfa00 &obj_c.m_d=0x7fffc1edfa04 &obj_c=0x7fffc1edf9f0 A::m_a=84, A::m_b=23, B::m_c=95 C::m_b=23, C::m_c=95, C::m_d=60 m_a=84, m_b=23, m_c=95假设 obj_c 的起始地址为 0x1300,那么它的内存分布如下图所示
当基类 A、B 的成员变量被遮蔽时,仍然会留在派生类对象 obj_c 的内存中,C 类新增的成员变量始终排在基类 A、B 的后面。 总结:在派生类的对象模型中,会包含所有基类的成员变量。这种设计方案的优点是访问效率高,能够在派生类对象中直接访问基类变量,无需经过好几层间接计算。
欢迎分享,转载请注明来源:内存溢出
C++继承时的对象内存位置(一)有成员变量遮蔽时的内存分布
赞
(0)
打赏
微信扫一扫
支付宝扫一扫
零基础学习c++第七记(进制转换,十进制转化为十六进制)
上一篇
2022-11-17
C语言基础——求1加到100的和
下一篇
2022-11-17
评论列表(0条)