设计一个 Rectangle 类来表示矩形。包含以下成员: ①两个数据成员 width 和 height,分别代表矩形的宽和高,缺省值都为 1; ②缺省函数 Rectangle( )用来创建一个缺省的矩形; ③带参构造函数 Rectangle(int width, int height)用来创建一个指定宽和高的矩形; ④两个获取数据成员的函数 getWidth( )和 getHeight( )分别用来获取 width 和 height 的值; ⑤两个赋值函数 setWidth(int newWidth)和 setHeight(int newHeight)分别为两个数据成员赋值; ⑥成员函数 getArea( )返回矩形的面积; ⑦成员函数 getPerimeter( )返回矩形的周长。 (1)实现这个类;编写程序创建两个 Rectangle 对象,一个对象的宽和高分别是 4 和 40,另一个对象的宽和高分别是 3.5 和 35.9;显示两个对象的数据成员的值、面积和周长。 (2)使用(1)定义的 Rectangle 类,在该类中声明一个友元函数 print_Rectangle( ), 编写该函数用来打印出 Rectangle 类的私有成员 length 和 width。创建一个 Rectangle 对象,调用 print_Rectangle( )函数进行测试。
代码如下,如有帮助,请采纳一下,谢谢。
#include <stdio.h>
class Rectangle
{
private:
int width,height;
public:
Rectangle(){width = 1; height = 1;}
Rectangle(int width,int height):width(width),height(height){}
int getWidth(){return width;}
int getHeight(){return height;}
void setWidth(int newWidth){width = newWidth;}
void setHeight(int newHeight){height = newHeight;}
int getArea(){return width * height;}
int getPerimeter(){return 2*(width + height);}
friend void print_Rectangle(Rectangle* p);
};
void print_Rectangle(Rectangle* p)
{
printf("width=%d;height=%d\n",p->width,p->height);
}
int main()
{
Rectangle r1(4,40);
Rectangle r2(3.5,35.9);
printf("r1的宽=%d;高=%d;面积=%d;周长=%d\n",r1.getWidth(),r1.getHeight(),r1.getArea(),r1.getPerimeter());
printf("r2的宽=%d;高=%d;面积=%d;周长=%d\n",r2.getWidth(),r2.getHeight(),r2.getArea(),r2.getPerimeter());
//
printf("友元函数测试:\n");
Rectangle r3(4,5);
print_Rectangle(&r3);
//getchar();
//getchar();
return 0;
}
class Rectangle
{
private:
float width;
float height;
public:
Rectangle() { width = height = 1; }
Rectangle(float w, float h) { width = w; height = h; }
float getWidth() { return width; }
float getHeight() { return height; }
void setWidth(float w) { width = w; }
void setHeight(float h) { height = h; }
float getArea() { return width*height; }
float getPerimeter() { return 2 * (width + height); }
friend void print_Rectangle(Rectangle &r) { printf("width=%g,height=%g\n", r.width, r.height); }
};
int main()
{
Rectangle r1(4, 40);
Rectangle r2(3.5, 35.9);
printf("矩形r1长=%g,宽=%g,面积=%g,周长=%g\n", r1.getWidth(), r1.getHeight(), r1.getArea(), r1.getPerimeter());
printf("矩形r2长=%g,宽=%g,面积=%g,周长=%g\n", r2.getWidth(), r2.getHeight(), r2.getArea(), r2.getPerimeter());
Rectangle r3(10, 30.2);
print_Rectangle(r3);
return 0;
}
题主,你确定采纳的代码能用吗?长和宽都是小数,用%d输出你能用啊?
您好,我是有问必答小助手,您的问题已经有小伙伴解答了,您看下是否解决,可以追评进行沟通哦~
如果有您比较满意的答案 / 帮您提供解决思路的答案,可以点击【采纳】按钮,给回答的小伙伴一些鼓励哦~~
ps:问答VIP仅需29元,即可享受5次/月 有问必答服务,了解详情>>>https://vip.csdn.net/askvip?utm_source=1146287632