C++复习要点总结十一——多态(二)
2016-04-06 20:40
411 查看
一 构造函数中能调用虚函数,实现多态吗
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 ;
}
相关文章推荐
- VS2010 C++读写.mat格式文件
- 状态模式(state)C++实现
- C++中的异常浅析
- 【C++】多文件程序结构
- c++中.dll与.lib文件的生成与使用的详解
- c语言的问卷调查
- c++操作符重载
- C语言的知识与能力的自评
- C++命名空间理解
- c++覆盖 重载 隐藏 的关系
- C++编程思想第二章练习答案
- lamda:和c++差不多
- Sublime text2 C/C++ 编译环境设置
- POJ 2236-Wireless Network(并查集)
- C语言入门基础篇,内存与变量关系
- C++入门基础知识:类和引用
- C++基础学习教程(六)----类编写的前情回想以及项目实战(1)
- Eclipse CDT MinGW生成C++动态链接库及Java JNI的调用例子
- C语言 格式问题
- C++Primer_笔记_异常处理