一 构造函数中能调用虚函数,实现多态吗
1)对象中的vptr指针什么时候被初始化?
对象在创建的时,由编译器对vptr指针进行初始化
只有当对象的构造完全结束后vptr的指向才最终确定
父类对象的vptr指向父类虚函数表
子类对象的vptr指向子类虚函数表
class parent
{ public:
parent(int a=0)//执行时此时的调用的print函数仍然是父类的函数(此时会将vptr指针指向父类的虚函数表)
{
this->a = a;
print();
}
virtual void print()
{
cout<<"我是爹"<<endl;
}
private:
int a;
};
class child : public parent
{ public:
child(int a = 0, int b=0):parent(a)//先执行父类构造器,执行完之后返回子类(vprt指针指回子类虚函数表)
{
this->b = b;
print();
}
virtual void print()
{
cout<<"我是儿子"<<endl;
}
private:
int b;
};
void howtoplay(parent *base)
{
base->print(); //有多态发生 //2 动手脚
}
void main()
{
child c1; //定义一个子类对象 ,在这个过程中,在父类构造函数中调用虚函数print 能发生多态吗?
system("pause");
return ;
}
二 父类指针步长和子类指针步长不一致时
class parent
{
public:
parent(int a=0)
{
this->a = a;
}
virtual void print()
{
cout<<"我是爹"<<endl;
}
private:
int a;
};
//成功 ,一次偶然的成功 ,必然的失败更可怕
class child : public parent
{
public:
/*
child(int a = 0, int b=0):parent(a)
{
this->b = b;
print();
}
*/
child(int b = 0):parent(0)
{
//this->b = b;
}
virtual void print()
{
cout<<"我是儿子"<<endl;
}
private:
//int b;
};
void howtoplay(parent *base)
{
base->print(); //有多态发生 //2 动手脚
}
void main()
{
child c1; //定义一个子类对象 ,在这个过程中,在父类构造函数中调用虚函数print 能发生多态吗?
//c1.print();
parent *pp = null;
child *pc = null;
child array[] = {child(1), child(2), child(3)};
pp = array;
pc = array;
pp->print();
pc->print(); //多态发生
pp++;
pc++;
pp->print();
pc->print(); //多态发生
pp++;
pc++;
pp->print();
pc->print(); //多态发生
cout<<"hello..."<<endl;
system("pause");
return ;
}
以上就是c++复习要点总结十一——多态(二)的内容。