Shape系列-2

Shape系列-2

时间: 1ms        内存:128M

描述:

小聪不喜欢小强的Shape类,声称用Shape类做出的形状不真实,于是小聪创建了Rectangle类,并且决定用该类做两个矩形出来,送给好朋友小亮。Rectangle类有整型的数据成员color(小强的Shape类中的color可以继续使用,无需新定义),浮点型的数据成员widthheight,求面积的成员函数area()。但是小聪没有为Rectangle类写构造函数和成员函数,请帮助小聪完成Rectangle类。

小强写的文件头和Shape类:

#include<iostream>

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;
}
小聪的测试函数:
int main()
{
Rectangle rr=Rectangle(1,2,3);
cout<<"Rectangle color:"<<rr.getcolor()<<endl
<<"Rectangle width:"<<rr.getwidth()<<endl
<<"Rectangle height:"<<rr.getheight()<<endl
<<"Rectangle area:"<<rr.area()<<endl
<<"Rectangle price:"<<rr.price()<<endl;
return 0;
}
提示:不用提交全部程序,只提交补充部分。

输入:

输出:

输出小聪创建的矩形的相关数据

示例输入:

示例输出:

Rectangle color:1
Rectangle width:2
Rectangle height:3
Rectangle area:6
Rectangle price:6

提示:

参考答案(内存最优[1088]):

#include<stdio.h>
int main()
{
	printf("Rectangle color:1\nRectangle width:2\nRectangle height:3\nRectangle area:6\nRectangle price:6\n");
}

参考答案(时间最优[0]):


#include<iostream>
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;
}
int main()

{
	Rectangle rr=Rectangle(1,2,3);
	cout<<"Rectangle color:"<<rr.getcolor()<<endl
		<<"Rectangle width:"<<rr.getwidth()<<endl
		<<"Rectangle height:"<<rr.getheight()<<endl
		<<"Rectangle area:"<<rr.area()<<endl
		<<"Rectangle price:"<<rr.price()<<endl;
	return 0;
}

题目和答案均来自于互联网,仅供参考,如有问题请联系管理员修改或删除。

点赞

发表评论

电子邮件地址不会被公开。必填项已用 * 标注