new的对象是谁,其调用virtual函数时,即调用谁
class father
{
public:
virtual void v_pp()
{
printf("this is virtual father");
}
void pp()
{
printf("this is father");
}
};
class child
{
public:
void v_pp()
{
printf("this is virtual child");
}
void pp()
{
printf("this is child");
}
void c_for_p()
{
parent::v_pp();
}
};
int main()
{
child *c = new child();
child *p = c;
//子类访问父类函数
c->c_for_p();//this is virtual parent;
c->v_pp(); //this is virtual child;
p->v_pp(); //this is virtual child;
c->pp(); //this is child;
p->pp(); //this is father;
p = new father();
c = p;
c->v_pp(); //this is virtual father;
p->v_pp(); //this is virtual father;
c->pp(); //this is child;
p->pp(); //this is father;
}
无virtual关键字时,new的对象是谁,其调用非virtual函数时,即调用谁
此处实际上是c++的隐藏属性
如上代码中的pp即为此功能
子类如何调用父类函数
parent::v_pp()用类名::函数名,即可在子类中访问父类的函数,但要注意的是,父类必须有virtual字段,子类的函数名和形参也必须要和父类的一致,即要打破c++的覆盖属性。