c++定义一个矩形类Rectangle
时间: 2023-12-14 17:30:53 浏览: 75
矩形类Rectangle可以定义如下:
```
class Rectangle{
public:
Rectangle(); // 默认构造函数
Rectangle(const Rectangle& p); // 复制构造函数
Rectangle(double a, double b, double c, double d); // 直接输入的构造函数
void input(); // 输入函数
void output(); // 输出函数
double area(); // 计算面积的函数
private:
double x1, x2, y1, y2; // 矩形的两个对角点坐标
};
```
其中,构造函数可以有三种形式,分别是默认构造函数、复制构造函数和直接输入的构造函数。输入函数和输出函数分别用于输入和输出矩形的坐标信息。计算面积的函数可以根据矩形的两个对角点坐标计算出矩形的面积。完整的代码如下:
```
#include <iostream>
using namespace std;
class Rectangle{
public:
Rectangle(); // 默认构造函数
Rectangle(const Rectangle& p); // 复制构造函数
Rectangle(double a, double b, double c, double d); // 直接输入的构造函数
void input(); // 输入函数
void output(); // 输出函数
double area(); // 计算面积的函数
private:
double x1, x2, y1, y2; // 矩形的两个对角点坐标
};
Rectangle::Rectangle(){
x1 = 0, x2 = 0, y1 = 0, y2 = 0;
}
Rectangle::Rectangle(const Rectangle& p){
x1 = p.x1, x2 = p.x2, y1 = p.y1, y2 = p.y2;
}
Rectangle::Rectangle(double a, double b, double c, double d){
x1 = a, y1 = b, x2 = c, y2 = d;
}
void Rectangle::input(){
cin >> x1 >> y1 >> x2 >> y2;
}
void Rectangle::output(){
cout << area() << endl;
}
double Rectangle::area(){
return (x2 - x1) * (y2 - y1);
}
int main(){
Rectangle p1;
p1.input();
p1.output();
Rectangle p2(p1);
p2.output();
Rectangle p3(1, 1, 6, 3);
p3.output();
return 0;
}
```