参考:https://www.cnblogs.com/wanmeishenghuo/p/9581270.html
参考文章:https://coolshell.cn/articles/12176.html
测试代码:
#include <iostream> #include <string> using namespace std; class Demo { protected: int mi; int mj; public: virtual void print() { cout << "mi = " << mi << ", " << "mj = " << mj << endl; } }; class Bro { public: int mb; void print111() { cout << "mj = " << mb << endl; } }; class Derived : public Demo { int mk; Bro bro; public: Derived(int i,int j,int k, int b) { mi = i; mj = j; mk = k; bro.mb= b; } void print() { cout << "mi = " << mi << ", " << "mj = " <<mj<< ", " << "mk = " << mk << ", " << "bro.mb= " << bro.mb << endl; } }; struct Test { void* p; int mi; int mj; int mk; int mb; }; int main() { cout << "sizeof(Demo) = " << sizeof(Demo) << endl; cout << "sizeof(Bro) = " << sizeof(Bro) << endl; cout << "sizeof(Derived) = " << sizeof(Derived) << endl; Derived d(1, 2, 3,4); Test* p = reinterpret_cast<Test*>(&d); cout << "Before changing ..." << endl; d.print(); p->mi = 10; p->mj = 20; p->mk = 30; p->mb = 40; cout << "After changing ..." << endl; d.print(); return 0; }
运行结果: