题目
题干给出一个类
class point{
int x;
int y;
public:
void setxy(int a, int b){x=a;y=b;}
int getx(){return x;}
int gety(){return y;}
}
要求设计矩形类,该矩形类继承point类,属性有长宽和左上角坐标,并有以下功能:
1.可以由用户输入矩形的左上角坐标和长宽
2.可以显示矩形的诸属性
3.可以求得并输出该矩形的周长和面积
题解
#include<iostream>
using namespace std;
class Point {
public:
int x;
int y;
public:
void setxy(int a, int b) {
x = a;
y = b;
}
int getx() {
return x;
}
int gety() {
return y;
}
};
class Rectangle :public Point {
public:
int width, length;
public:
Rectangle() {
int x, y;
cout << "输入左上角坐标:";
cin >> x >> y;
setxy(x, y);
cout << "输入宽度和长度:";
cin >> width >> length;
cout << "该矩形四个顶点的坐标为:" << "(" << x << "," << y << ")" << " "
<< "(" << x + length << "," << y << ")" << " "
<< "(" << x + length << "," << y - width << ")" << " "
<< "(" << x << "," << y - width << ")" << " "<<endl;
}
void setWidth(int w) {
width = w;
}
void setLength(int I) {
length = I;
}
int getArea() {
cout << "面积为:" << width * length;
return width * length;
}
int getZC() {
cout << "周长为:" << 2 * (width + length);
return 2 * (width + length);//返回周长
}
};
int main(int argc,char*argv[]){
Rectangle rec;//类实例化,创建对象
rec.getArea();
rec.getZC();//求该对象的周长
return 0;
}
知识补充
1.int main(int argc,char* argv[])
argc是命令行总的参数个数
argv[]是argc个参数,其中第0个参数是程序的全名,以后的参数是命令行后面跟的用户输入的参数
是main函数的最标准写法。