类型兼容原则遇上函数重写

来源:互联网 发布:阿里云 物理专线 编辑:程序博客网 时间:2024/06/06 02:43

1、面向对象新需求

编译器的做法不是我们期望的

         根据实际的对象类型来判断重写函数的调用

         如果父类指针指向的是父类对象则调用父类中定义的函数

         如果父类指针指向的是子类对象则调用子类中定义的重写函数

这个新的需求就是多态


#include<iostream>using namespace std;class Parent{public:Parent (int a){this->a = a;cout<<"a: "<<a<<endl;}virtual void print()//在父类同名函数写了virtual关键字后子类可写可不写{cout<<"Parent 打印a: "<<a<<endl;}protected:private:int a;};class child:public Parent{public:child (int b):Parent(10){this->b = b;cout<<"b: "<<b<<endl;}void print(){cout<<"Child 打印b: "<<b<<endl;}protected:private:int b;};void howToPrint(Parent *base){base->print();}void howToPrint2(Parent &base){base.print();}int main(){Parent *base = NULL;Parent p1(20);child c1(30);base = &p1;base->print();//执行父类的大隐函数base = &c1;base->print();//执行谁的函数?----面向对象新需求{Parent &base2 = p1;base2.print();Parent &base3 = c1;//base3是c1的别名base3.print();}//函数调用howToPrint(&p1);howToPrint(&c1);howToPrint2(p1);howToPrint2(c1);system("pause");return 0;}




0 0
原创粉丝点击