C++复习要点总结十一——多态(二)

黄舟
发布: 2017-01-16 11:53:36
原创
1302人浏览过

一 构造函数中能调用虚函数,实现多态吗

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 ;
}
登录后复制

68.png

二 父类指针步长和子类指针步长不一致时

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 ;
}
登录后复制

69.png

以上就是C++复习要点总结十一——多态(二)的内容,更多相关内容请关注PHP中文网(www.php.cn)!

立即学习C++免费学习笔记(深入)”;

c++速学教程(入门到精通)
c++速学教程(入门到精通)

c++怎么学习?c++怎么入门?c++在哪学?c++怎么学才快?不用担心,这里为大家提供了c++速学教程(入门到精通),有需要的小伙伴保存下载就能学习啦!

下载
来源:php中文网
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn
最新问题
开源免费商场系统广告
热门教程
更多>
最新下载
更多>
网站特效
网站源码
网站素材
前端模板
关于我们 免责申明 意见反馈 讲师合作 广告合作 最新更新
php中文网:公益在线php培训,帮助PHP学习者快速成长!
关注服务号 技术交流群
PHP中文网订阅号
每天精选资源文章推送
PHP中文网APP
随时随地碎片化学习
PHP中文网抖音号
发现有趣的

Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号