C++多态

ifndef _FRACT_H_
#define _FRACT_H_
#include <iostream>
using namespace std;

class Fract
{
	int n;//分子
	int d;//分母
public:
	Fract() :n(0), d(1)
	{};
	Fract(int an, int ad) :n(an), d(ad)
	{};

	virtual void show()
	{
		cout << "父类show被调用了!" << endl;
	}

	int value()
	{
		return n*d;
	}

};

class Dai :public Fract
{
	int m;
public:
	Dai() :m(0), Fract(1, 1)
	{}
	Dai(int am, int an, int ad) :m(am), Fract(an, ad)
	{}
	void show()
	{
		cout << "子类show被调用了!" << endl;
	}
	int value()
	{
		return m*Fract::value();
	}
};
#endif

#include"Fract.h"
#include<iostream>

using namespace std;

int main()
{
	Fract f;
	f.show();
	cout << "f=" << f.value() << endl;
	Dai f1;
	f1.show();
	cout << "f1=" << f1.value() << endl;
	//此处用指针调用show,因为指针p还是Fract对象,因此此处仍然调用的是
	//父类Fract的show
	//把父类中的show声明为虚函数,则show就具有多态性,在调用show的时候
	//会根据对象的实际内容调用相应的方法,在这里,因为指针p是Fract父类对象
	//但是p指向的是Dai对象,即p实际的内容是Dai对象,因此在把父类中的show声明为
	//虚函数之后,此处调用的就是子类Dai中的show,而不是父类的show
	//除了指针,还有引用也是这样
	Fract* p = NULL;
	p = &f1;
	p->show();

	system("pause");
	return 0;
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值