C++虚函数

/*********************************************************************************
        如果想在基类中定义一个成员留待子类中进行细化,我们必须在它前面加关 
	    键字virtual ,以便可以使用指针对指向相应的对象进行操作。
**********************************************************************************/
#include <iostream>//
using namespace std;
class Test
{
protected:
	int height;
	int width;
public:
	void setvalue(int a,int b)
	{
		height=a;
		width=b;
	}
	virtual int area()
	{
		return 0;
	}
};
class Rectangle:public Test
{
public:
	int area()
	{
		return (height*width);
	}
};
class Triangle:public Test
{
public:
	int area()
	{
		return (height*width/2);
	}
};
void main()
{
	Rectangle rect;
	Triangle tri;
	Test test;
	Test *test1=▭
	Test *test2=&tri;
	Test *test3=&test;
	test1->setvalue(3,4);
	test2->setvalue(3,4);
	test3->setvalue(3,4);
	cout<<"长方形面积为:"<<test1->area()<<endl;
	cout<<"三角形面积为:"<<test2->area()<<endl;
	cout<<"Test面积为:"<<test3->area()<<endl;
	getchar();
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值