One possible implementation of this class is shown below:
// Rectangle.hclass Rectangle { private: double width; // width of the rectangle
double height; // height of the rectangle
double x; // x-coordinate of the top-left corner
double y; // y-coordinate of the top-left corner
public: // default constructor that creates a unit square at (0, 0)
Rectangle(); // constructor that creates a rectangle with given width, height and coordinates
Rectangle(double w, double h, double x1, double y1); // accessor methods for data fields
double getWidth() const; double getHeight() const; double getX() const; double getY() const; // mutator methods for data fields
void setWidth(double w); void setHeight(double h); void setX(double x1); void setY(double y1); // method that returns the area of the rectangle
double getArea() const; // method that returns the perimeter of the rectangle
double getPerimeter() const;
};// Rectangle.cpp#include "Rectangle.h"// default constructor that creates a unit square at (0, 0)Rectangle::Rectangle() {
width = 1;
height = 1;
x = 0;
y = 0;
}// constructor that creates a rectangle with given width, height and coordinatesRectangle::Rectangle(double w, double h, double x1, double y1) {
width = w;
height = h;
x = x1;
y = y1;
}// accessor methods for data fieldsdouble Rectangle::getWidth() const { return width;
}double Rectangle::getHeight() const { return height;
}double Rectangle::getX() const { return x;
}double Rectangle::getY() const { return y;
}// mutator methods for data fieldsvoid Rectangle::setWidth(double w) {
width = w;
}void Rectangle::setHeight(double h) {
height = h;
}void Rectangle::setX(double x1) {
x = x1;
}void Rectangle::setY(double y1) {
y = y1;
}// method that returns the area of the rectangledouble Rectangle::getArea() const { return width * height;
}// method that returns the perimeter of the rectangledouble Rectangle::getPerimeter() const { return (width + height) *2;
}
You can use this class to create objects representing rectangles and call their methods to get their properties. For example:
#include <iostream>#include "Rectangle.h"using namespace std;int main(){ // create a rectangle object with width=3, height=4 and coordinates=(2,-5)
Rectangle r(3.0 ,4.0 ,2.0 ,-5.0); // print its area and perimeter
cout << "The area of r is " << r.getArea() << endl;
cout << "The perimeter of r is " << r.getPerimeter() << endl; return 0;
}
温馨提示:答案为网友推荐,仅供参考