通过程序理解虚函数的实现与访问

#include<iostream>
using namespace std;
class Poin //定义基类
{
public:
	Poin(double a = 0, double b = 0) { x = a, y = b; }
	virtual double area()               //必须在基类中必须定义虚函数,
										//在派生类中重新定义时,
										//其函数原型,包括返回类型、函数名、参数个数、参数类型的顺序,
										//都必须与基类中的原型完全相同。
	{
		cout << "基类定义虚函数的返回值:";
		return 0.0;
	}
protected:
	double x, y;
};

class rectangle :public Poin//公用派生类(若要使用虚函数,派生类应该从它的基类公用派生)
{
public:
	rectangle(double a = 0, double b = 0, double c = 0, double d = 0) :Poin(a, b)
	{
		x1 = c; y1 = d;
	}
	virtual	double area()
	{
		cout << "矩形面积:";
		return (x - x1)*(y - y1);
	}
protected:
	double x1, y1;
};
///
class circle :public Poin 公用派生类
{
public:
	circle(double a = 0, double b = 0, double c = 0) :Poin(a, b)
	{
		r = c;
	}
	virtual double area()
	{
		cout << "圆面积:";
		return 3.14*r*r;
	}
protected:
	double r;
};
/
double calcarea(Poin &ref)//类外的自定义函数
{
	return (ref.area());	//在基类中没有将area定义为虚函数时,返回类Pion里的area函数里的返回值;
							//在基类中将area定义为虚函数后,
							//则会根据调用此函数的语句中的实参的类型(是基类对象、还是派生类对象),
							//然后动态地将area指定为基类中的area还是派生类中的area
}
//
int main()
{
	Poin p(0, 0), *K = &p;
	rectangle r(0, 0, 1, 1), *E = &r;		
	circle c(0, 1, 1), *H = &c;
	cout << "通过——类对象的引用——访问虚函数:" << calcarea(p) << endl;//calcarea()是定义的一个普通函数,形参为类对象的引用
	cout << "通过——类对象的指针——访问虚函数:" << K->area() << endl << endl;

	cout << "通过——类对象的引用——访问虚函数:" << calcarea(r) << endl;
	cout << "通过——类对象的指针——访问虚函数:" << E->area() << endl << endl;

	cout << "通过——类对象的引用——访问虚函数:" << calcarea(c) << endl;
	cout << "通过——类对象的指针——访问虚函数:" << H->area() << endl << endl;
	return 0;
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值