您的位置:首页 > 编程语言 > C语言/C++

C++虚函数

2013-12-15 20:05 225 查看
/*********************************************************************************
如果想在基类中定义一个成员留待子类中进行细化,我们必须在它前面加关
键字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();
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: