首先我们要知道矩形的构成元素是啥,长(height),宽(width),这是矩形最基本的两个要素,话不多说,直接上代码。
一:我们首先定义一个类Rectangle
#includeusing namespace std; class Rectangle { private: int height; //长 int width; //宽 public: Rectangle(int height, int width); int getZhou(); //这个函数是用来求周长的 int getArea(); //这个函数是用来求面积的 void print1(int x); void print2(int z); };
然后我们在类外部定义函数
Rectangle::Rectangle(int height , int width) {
this->height = height; //把外部输入的长的值赋值给类内部的长
this->width = width; //把外部输入的宽的值赋值给类内部的宽
}
int Rectangle::getZhou() {
return (height + width ) * 2; //求周长
}
int Rectangle::getArea() { //求面积
return height * width;
}
void Rectangle::print1(int x) { //在控制台打印周长的值
cout << "周长为:" << x << endl;
}
void Rectangle::print2(int z) { //在控制台打印面积的值
cout << "面积为:" << z << endl;
}
二:main方法也就是主函数中的代码
int main() {
int height;
int width;
cout << "请输入长度:" << endl; //从控制台输入长的值
cin >> height;
cout << "请输入宽度:" << endl; //从控制带输入宽的值
cin >> width;
Rectangle Rectangle(height , width); //把外部输入的长和宽的值赋值给类内部的长和宽
cout << "******************" << endl;
cout << "1:求周长" << endl; //从控制台选择操作
cout << "2:求面积" << endl;
cout << "3:结束" << endl;
cout << "******************" << endl;
int r = Rectangle.getZhou(); //由类中函数完成,并把周长值导出
int z = Rectangle.getArea(); //由类中函数完成,并把面积值导出
while(true){ //设置一个死循环
int x;
cin >> x;
if ( x == 1){
Rectangle.print1(r); //选择1,在控制台打印周长值
} else if (x == 2){
Rectangle.print2(z); //选择2,在控制台打印面积值
} else if (x == 3){
break; //选择3,结束循环并且结束程序
}
}
return 0;
}



