/*********************************************************************************
如果想在基类中定义一个成员留待子类中进行细化,我们必须在它前面加关
键字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();
}
C++虚函数
最新推荐文章于 2022-07-07 21:29:29 发布