抽象类(有纯虚函数的类) / 虚基类
virtual:
1.修饰成员方法是虚函数
2.可以修饰继承方式,是虚继承。被虚继承的类,称作虚基类。
vfptr/vbptr
vftable/vbtable
在Windows vs下会存在内存释放错误的问题,Linux g++下自动修正。
命令:cl 继承与多态.cpp /d1reportSingleClassLayout 可以查看内存布局。
#include <iostream>
#include <string>
using namespace std;
class A {
public:
virtual void func() { cout << "call A::func" << endl; }
void operator delete(void *ptr) {
cout << "operator delete p:" << ptr << endl;
free(ptr);
}
private:
int ma;
};
class B : virtual public A {
public:
void func() { cout << "call B::func" << endl; }
void *operator new(size_t size) {
void *p = malloc(size);
cout << "operator new p:" << p << endl;
return p;
}
private:
int mb;
};
/*
A a; 4个字节
B b; ma,mb 8个字节+4 = 12个字节 vbptr
*/
int main() {
基类指针指向派生类对象,永远指向的是派生类基类部分数据的起始地址
//A *p = new B(); // B::vftable
//p->func();
//delete p;
B b;
A *p = &b;
p->func();
return 0;
}