以下用来学习基类指针指向子类对象时的情况
即Base *pB = new Derived();
分析其创建过程:
1.new一个子类对象,为其生成一个指向该种子类虚函数表VTable的指针vptr,指向Derived::func();
2.创建一个基类指针指向它,基类没有的成员变量将无法通过该指针解引用后调用,但vptr还是那个vptr,vptr指向的虚函数表里还是Derived::func();
目前来看这种判断方法还没有出错
#include<iostream>
using namespace std;
class Base {
public:
Base() { cout << "Base Creted" << endl; }
~Base() { cout << "Base Destroyed" << endl; }
virtual void func() {
cout << "basefunc" << endl;
}
};
class Derived : public Base {
public:
Derived() { cout << "Derived Created" << endl; }
~Derived() { cout << "Derived Destroyed" << endl; }
virtual void func() {
cout << "derivedfunc" << endl;
}
/*int func(int a) {
cout << "basefunc222" << endl;
return 1;
}*/
};
int main()
{
Base *pB = new Derived();
pB->func();
// pB->func(1);
delete pB;
pB = NULL;
int l = 31ul;
cout << l << endl;
system("pause");
return 0;
}