多态从实现的角度分为:静态多态和动态多态
静态多态也叫做编译时多态
动态多态也叫做运行时多态
函数重载是多态的一种实现形式:
重载分为:
1.相同函数不同参数和类型的重载
2.不同类,相同函数重载
第二种的实现:
- #include <iostream>
- using namespace std;
- //定义father类
- class father
- {
- //定义私有成员
- private:
- int height;
- int weight;
- //定义公有成员
- public:
- int showh(int h)
- {
- height = h;
- return height;
- }
- int showw(int w)
- {
- weight = w;
- return weight;
- }
- };
- //son继承father
- class son:public father
- {
- //son的私有成员
- private:
- int height;
- int weight;
- //son的公有成员
- public:
- int showh(int h)
- {
- height = h;
- return height;
- }
- int showw(int w)
- {
- weight = w;
- return weight;
- }
- };
- //主函数
- int main()
- {
- //创建father对象
- father liming;
- cout<<"父亲的身高是: "<<liming.showh(170)<<endl;
- cout<<"父亲的体重是: "<<liming.showw(120)<<endl;
- //创建son对象
- son lilei;
- cout<<"儿子的身高是: "<<lilei.showh(160)<<endl;
- cout<<"儿子的体重是: "<<lilei.showw(100)<<endl;
- //儿子调用父亲的身高
- cout<<"父亲的身高是: "<<lilei.father::showh(170)<<endl;
- return 0;
- }
转载于:https://blog.51cto.com/nojob/318425