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

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
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值