继承对象模型
在c++编译器的内部类可以理解为结构体
子类是由父类成员叠加子类新成员得到的
继承对象模型的初探51-1:
#include <iostream>
#include <string>
using namespace std;
class demo
{
protected:
int mi;
int mj;
};
class derived:public demo
{
int mk;
public:
derived(int i,int j,int k)
{
mi = i;
mj = j;
mk = k;
}
void print()
{
cout<<"mi = "<<mi << ","
<<"mj = "<<mj << ","
<<"mk = "<<mk << endl;
}
};
struct Test
{
int mi;
int mj;
int mk;
};
int main()
{
cout<<"sizeof(demo) = "<<sizeof(demo)<<endl;
cout<<"sizeof(derived) = "<<sizeof(derived)<<endl;
derived d(1,2,3);
Test* p = reinterpret_cast<Test*>(&d);
cout<<"Before changing...."<<endl;
d.print();
p->mi = 10;
p->mj = 20;
p->mk = 30;
cout<<"After changing...."<<endl;
d.print();
return 0;
}
输出:
sizeof(demo) = 8
sizeof(derived) = 12
Before changing....
mi = 1,mj = 2,mk = 3
After changing....
mi = 10,mj = 20,mk = 30
多态对象模型
C++多态的实现原理
类中声明虚函数时,编译器会在类中生成一个虚函数表
虚函数表时一个存储成员函数地址的数据结构
虚函数表是由编译器自动生成与维护的
virtual成员函数会被编译器放入虚函数表中
存在虚函数时,每个对象中都有一个指向虚函数的指针
调用虚函数存在三次寻址
#include <iostream>
#include <string>
using namespace std;
class demo
{
protected:
int mi;
int mj;
virtual void print()
{
cout<<"mi = "<<mi << ","
<<"mj = "<<mj << endl;
}
};
class derived:public demo
{
int mk;
public:
derived(int i,int j,int k)
{
mi = i;
mj = j;
mk = k;
}
void print()
{
cout<<"mi = "<<mi << ","
<<"mj = "<<mj << ","
<<"mk = "<<mk << endl;
}
};
struct Test
{
void* p;
int mi;
int mj;
int mk;
};
int main()
{
cout<<"sizeof(demo) = "<<sizeof(demo)<<endl;
cout<<"sizeof(derived) = "<<sizeof(derived)<<endl;
derived d(1,2,3);
Test* p = reinterpret_cast<Test*>(&d);
cout<<"Before changing...."<<endl;
d.print();
p->mi = 10;
p->mj = 20;
p->mk = 30;
cout<<"After changing...."<<endl;
d.print();
return 0;
}
输出:
sizeof(demo) = 12
sizeof(derived) = 16
Before changing....
mi = 1,mj = 2,mk = 3
After changing....
mi = 10,mj = 20,mk = 30
**粗体** _斜体_ [链接](http://example.com) `代码` - 列表 > 引用
。你还可以使用@
来通知其他用户。