先写一个基类Base 再写一个派生类derive简单实现它们的构造虚构函数
class Base
{
public:
Base(int data = 0) :ma(data)
{
cout << "Base()" << endl;
}
void Show()
{
cout << "Base::Show()" << endl;
}
void Show(int data)
{
cout << "Base::Show(int)" << endl;
}
void* operator new(size_t size)
{
int *p = (int*)malloc(size);
cout <<"new::"<< p << endl;
if (p == NULL)
{
throw bad_alloc();
}
return p;
}
void operator delete(void* ptr)
{
cout << "delete::"<<ptr << endl;
free(ptr);
}
~Base()
{
cout << "~Base()" << endl;
}
protected:
int ma;
};
class Derive : public Base
{
public:
Derive(int data) :mb(data), Base(data)
{
cout << "Derive()" << endl;
}
virtual void Show()//编译器认为这个函数也是虚函数
{
cout << "Derive::Show()" << endl;
}
~Derive()
{
cout << "~Derive()" << endl;
}
private:
int mb;
};
{
Base b(10);
Derive d(10);
//Base* p2 = &d;//基类的指针 指向派生类的对象
Base &d1 = d;//基类的引用可以引用派生类的对象
return 0;
}
{
Derive d(10);
Base* p = &d;
p->Show();
/*
Base 编译阶段 静态的绑定 早绑定 静态的多态 call Base::Show
函数重载 模板
*/
/*
运行时==>动态的绑定 晚绑定 运行时的多态
call eax
继承:虚函数
*/
cout << sizeof(Base) << endl;
cout << sizeof(Derive) << endl;
cout << typeid(p).name() << endl;//class Base*
cout << typeid(*p).name() << endl;//class Base
return 0;
}
{
Base b(10);
Derive d(20);
b.Show();//静态的多态
d.Show(); //静态的多态
p1->Show();动态的
p2->Show();//动态的多态base
p3->Show();//derive
}
虚函数
1.能取地址
2.对象
析构函数 可以
inline函数 不能
static函数 不能
*/
/*
1.什么时候会产生运行时多态的编译或者调用
指针指向或者引用时,调用虚函数
*/
{
/*
vfptr
Base::
ma
mb
*/
p->Show();
delete p;
//(*p).~Base();
/*
void free(void *ptr);
*/
return 0;
}