64,642
社区成员
发帖
与我相关
我的任务
分享
#include<iostream>
using namespace std;
class shape
{
public:
shape(double a,double b)
{
x=a;
y=b;
}
//基类中定义为纯虚函数
virtual void getarea()=0;
double getx(){return x;}
double gety(){return y;}
//基类应该为保护成员,这样才可以被派生类访问
protected:
double x,y;
};
class circle:public shape
{
public:
//构造函数的实现,调用基类的构造函数,注意参数
circle(double radius):shape( radius, radius)
{ }
void getarea()
{
cout<<x*x*3.14<<endl;
}
};
class square:public shape
{
public:
square(double height,double width):shape(height,width)
{ }
void getarea()
{
cout<<x*y<<endl;
}
};
class triangle:public shape
{
public:
triangle(double height,double under):shape(height,under)
{ }
void getarea()
{
cout<<x*y/2<<endl;
}
};
int main()
{
shape *p;
circle a(2);
p=&a;
p->getarea();
square b(3,3.4);
p=&b;
p->getarea();
triangle c(2,2.3);
p=&c;
p->getarea();
//system("pause");
return 0;
}