C++多态需求的引入

#include <iostream>
using namespace std;

class Parent
{
public:
	Parent(int a){
		this->a = a;
		cout<<"Parent a:"<<a<<endl;
	}
	void print(){
		cout<<"Parent 打印a:"<<a<<endl;
	}
private:
	int a;
};

class Child :public Parent
{
public:
	Child(int b):Parent(10){
		this->b = b;
		cout<<"Child b:"<<b<<endl;
	}
	void print(){
		cout<<"Child 打印b:"<<b<<endl;
	}
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(40);

	base =&p1;
	base->print();

	base = &c1;
	base->print();

	{
		Parent &base2 = p1;
		base2.print();

		Parent &base3 = c1;
		base3.print();
	}

	howToPrint(&p1);
	howToPrint(&c1);

	howToPrint2(p1);
	howToPrint2(c1);

	system("pause");
}

父类中被重写的函数依然会继承给子类,默认情况下子类中重写的函数将隐藏父类中的函数,通过作用域分辨符::可以访问到父类中被隐藏的函数。

这种现象产生的原因:

C/C++是静态编译型语言,在编译时,编译器自动根据指针的类型判断指向的是一个什么样的对象。静态链编

1、在编译此函数的时,编译器不可能知道指针 p 究竟指向了什么。

2、编译器没有理由报错。

3、于是,编译器认为最安全的做法是编译到父类的print函数,因为父类和子类肯定都有相同的print函数。

但是,在实际的过程应用中产生了这么一个新需求:根据实际的对象类型来判断重写函数的调用

//面向对象新需求

//如果我传一个父类对象,执行父类的print函数

//如果我传一个子类对象,执行子类的printf函数


解决方案

Ø C++中通过virtual关键字对多态进行支持

Ø 使用virtual声明的函数被重写后即可展现多态特性

#include <iostream>
using namespace std;

class Parent
{
public:
	Parent(int a){
		this->a = a;
		cout<<"Parent a:"<<a<<endl;
	}
	virtual void print(){
		cout<<"Parent 打印a:"<<a<<endl;
	}
private:
	int a;
};

class Child :public Parent
{
public:
	Child(int b):Parent(10){
		this->b = b;
		cout<<"Child b:"<<b<<endl;
	}
	void print(){
		cout<<"Child 打印b:"<<b<<endl;
	}
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(40);

	base =&p1;
	base->print();

	base = &c1;
	base->print();

	{
		Parent &base2 = p1;
		base2.print();

		Parent &base3 = c1;
		base3.print();
	}

	howToPrint(&p1);
	howToPrint(&c1);

	howToPrint2(p1);
	howToPrint2(c1);

	system("pause");
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值