Description
小聪送给小亮和小华的形状他们都很喜欢,小亮和小华非要比一下他们两个的形状,来看看小聪更爱谁,请完成RsubC类。RsubC类中包括Rectangle类和Circle类的数据成员,新增布尔类型的数据成员sign(sign等于0时,新面积等于Rectangle+Circle,sign等于1时,新面积等于Rectangle-Circle),新定义了求面积的成员函数area()。但是小聪没有为RsubC类写构造函数和成员函数,请帮助小聪完成RsubC类。
Input
无
Output
输出小聪测试的RsubC的面积。
Sample Output
RsubC area:2.86
代码:
#include<iostream>
#define PI 3.14
using namespace std;
class Shape
{
public:
Shape();
Shape(int c);
int getcolor();
double area();
protected:
int color;
};
Shape::Shape()
{
color=0;
}
Shape::Shape(int c)
{
color=c;
}
int Shape::getcolor()
{
return color;
}
double Shape::area()
{
return 10000;
}
class Rectangle:public Shape
{
public:
Rectangle(int c,double w,double h);
double getwidth();
double getheight();
double area();
double price();
protected:
double height;
double width;
};
Rectangle::Rectangle(int c,double w,double h):Shape(c)
{
width=w;
height=h;
}
double Rectangle::getwidth()
{
return width;
}
double Rectangle::getheight()
{
return height;
}
double Rectangle::area()
{
return height*width;
}
double Rectangle::price()
{
return height*width*color;
}
class Circle:public Shape
{
public:
Circle(int c,double r);
double getradius();
double area();
double price();
protected:
double radius;
};
Circle::Circle(int c,double r):Shape(c)
{
radius=r;
}
double Circle::getradius()
{
return radius;
}
double Circle::area()
{
return PI*radius*radius;
}
double Circle::price()
{
return PI*radius*radius*color;
}
class RsubC:public Rectangle,public Circle
{
public:
RsubC(int c1,float h,float w,int c2,float r):Rectangle(c1,h,w),Circle(c2,r) {}
float area()
{
float area;
if(sign==1)
area=Rectangle::area()-Circle::area();
if(sign==0)
area=Rectangle::area()+Circle::area();
return area;
}
private:
int sign=1;
};
int main()
{
RsubC rc=RsubC(1,2,3,1,1);
cout<<"RsubC area:"<<rc.area()<<endl;
return 0;
}
运行结果:
学习心得:
在这个程序中要求sign是布尔型的,但是我写成布尔型的运行结果没有错误,但是在OJ上提交就是错误的,不知道原因是什么,但是我根据同学的程序改了一下,把sign改成了int型的,然后给它赋值,编译出现了一个警告,但是运行结果是对的而且在OJ上提交也是对的,不明白为什么要用int型的。