c++ 多态
2015-07-06 11:09
501 查看
#include <iostream> #include <string> using namespace std; class Grandpa { protected: int age_; public: Grandpa(int age = 100) { age_ = age; cout << "对象Grandpa构造完成!" << endl; } int GetAge() { return doGetAge(); } virtual int doGetAge() { return age_; } }; class Parent : public Grandpa { protected: int age_; public: Parent(int age = 70) { age_ = age; cout << "对象Parent构造完成!" << endl; } int doGetAge() { return age_; } }; class Son : public Parent { protected: int age_; public: Son(int age = 40) { age_ = age; cout << "对象Son构造完成!" << endl; } }; void main() { Son son(10);//依次调用构造函数,初始化Grandpa的age_=100,Parent的age_=70,Son的age_=40 //以下调用结果一样,原因如下 //1.调用的主体是子类Son //2.调用的函数实际是虚函数doGetAge()----多态 cout << son.GetAge() << endl; cout << son.Grandpa::GetAge() << endl;// cout << son.Parent::GetAge() << endl; cout << son.Son::GetAge() << endl; //以下调用结果不一样,原因如下 //doGetAge()调用时直接指定了类名 cout << son.doGetAge() << endl;//70,继承自Parent cout << son.Grandpa::doGetAge() << endl;//100,Grandpa有实现doGetAge()方法 cout << son.Parent::doGetAge() << endl;//70 cout << son.Son::doGetAge() << endl;//70,继承自Parent cin.get(); }
相关文章推荐
- C语言内存分配
- 《C语言及程序设计》实践项目——敲了哪一个键?
- 《C语言及程序设计》实践参考——对称点
- 《C语言及程序设计》实践项目——枚举应用
- VC++2008中快速运用OpenCV打开图像文档
- VC++:结合设备安装类GUID和设备接口类GUID获取设备VIDPID
- 重新认识C语言
- 重新认识C语言
- C++实现循环队列之顺序存储
- QTC++ widget中使用QML编写的UI界面
- C++重载operator = 和初始化 =
- C++编译问题-检测到 Mac 文件格式: 请将源文件转换为 DOS 格式或 UNIX 格式
- VS2008切换环境(c#,c++,other)
- 【C++】栈空栈满异常处理
- chapter16test2
- C++拷贝构造函数详解
- ubuntu下用Eclipse完成C语言编程练习
- C++的深拷贝与浅拷贝
- 跳跃表(Skip List)的实现及测试 C++实现
- chapter16test1