#include <cstdio>
#include <iostream>
using namespace std;
//基类A
class A{
public:
A(int a, int b);
public:
int m_a;
int m_b;
};
A::A(int a, int b): m_a(a), m_b(b){ }
//基类B
class B{
public:
B(int b, int c);
public:
int m_b;
int m_c;
};
B::B(int b, int c): m_b(b), m_c(c){ }
//派生类C
class C: public A, public B{
public:
C(int a, int b, int c, int d);
public:
void display();
public:
int m_a;
int m_c;
int m_d;
};
C::C(int a, int b, int c, int d): A(a, b), B(b, c), m_a(a), m_c(c), m_d(d){ }
void C::display(){
printf("A::m_a=%d, A::m_b=%d\n", A::m_a, A::m_b);
printf("B::m_b=%d, B::m_c=%d\n", B::m_b, B::m_c);
printf("C::m_a=%d, C::m_c=%d, C::m_d=%d\n", C::m_a, C::m_c, m_d);
}
int main(){
C obj_c(10, 20, 30, 40);
obj_c.display();
cout<<"&obj_c.A::m_a="<<&obj_c.A::m_a<< " &obj_c.A::m_b="<<&obj_c.A::m_b<<"\n";
cout<< "&obj_c.B::m_b="<<&obj_c.B::m_b<<" &obj_c.B:m_c="<<&obj_c.B::m_c<<"\n";
//cout<<"&obj_c.C::m_a="<<&obj_c.C::m_a<<" &obj_c.m_c="<<&obj_c.C::m_c<<" &obj_c.C::m_d="<<&obj_c.C::m_d<<" &obj_c="<<&obj_c<<endl;
cout<<"&obj_c.m_a="<<&obj_c.m_a<<" &obj_c.m_c="<<&obj_c.m_c<<" &obj_c.m_d="<<&obj_c.m_d<<" &obj_c="<<&obj_c<<endl;
return 0;
}
A::m_a=10, A::m_b=20
B::m_b=20, B::m_c=30
C::m_a=10, C::m_c=30, C::m_d=40
&obj_c.A::m_a=0x7ffe5583e970 &obj_c.A::m_b=0x7ffe5583e974
&obj_c.B::m_b=0x7ffe5583e978 &obj_c.B:m_c=0x7ffe5583e97c
&obj_c.m_a=0x7ffe5583e980 &obj_c.m_c=0x7ffe5583e984 &obj_c.m_d=0x7ffe5583e988 &obj_c=0x7ffe5583e970
A、B 是基类,C 是派生类,假设 obj_c 的起始地址是 0X1000,那么 obj_c 的内存分布如下图所示:
基类对象的排列顺序和继承时声明的顺序相同。