例子引出
#include <iostream>
using namespace std;
class Parent
{
public:
Parent(int a = 0)
{
this->a = a;
}
virtual void print()
{
cout<<"Parent"<<endl;
}
protected:
private:
int a;
};
class Child :public Parent
{
public:
Child(int a = 0,int b = 0):Parent(2)
{
this->b = b;
}
void print()
{
cout<<"Child"<<endl;
}
protected:
private:
int b;
};
void howToPrint(Parent *p)
{
p->print();
}
int main()
{
Parent p;
Child c;
//cout<<sizeof(p)<<endl;//4 Parent类和Child类不加virtual关键字时
//cout<<sizeof(c)<<endl;//8
cout<<sizeof(p)<<endl;//8 当Parent类的print函数加virtual关键字时
cout<<sizeof(c)<<endl;//12 Parent类和Child类的大小都增加了4个字节===vptr指针
howToPrint(&p);
howToPrint(&c);
system("pause");
return 0;
}
思考:C++是如何实现多态的呢?当我们不加virtual关键字的