Bài tập C++ oop: tạo các setter, getter, constructor cho lớp Rectangle | Codelearn

  • TuanLQ7
  • Easy
  • 100 Points

Task

Create a Rectangle class in Rectangle.cpp file with the following information:

Explanation:

  • length and width are the attributes that describe the length and width of a rectangle.
  • Rectangle() is the no-arg constructor.
  • Rectangle(length: double, width: double) is the parameterized constructor used to initialize values to length and width.
  • setLength(length: double), getLength(), setWidth(width: double), getWidth()are setter and getter.
  • getArea() method returns the area of a rectangle.
  • getPerimeter() method returns the perimeter of a rectangle

A program to test the above Rectangle class:

#include<iostream>
#include "Rectangle.cpp"

using namespace std;

int main() {
	Rectangle r(4, 5);
	cout << "Area: " << r.getArea() << endl;
	cout << "Perimeter: " << r.getPerimeter() << endl;
	r.setLength(2);
	r.setWidth(3);
	cout << "Area: " << r.getArea() << endl;
	cout << "Perimeter: " << r.getPerimeter() << endl;
	return 0;
}

When the above code is compiled and executed, it produces the following result:

Area: 20
Perimeter: 18
Area: 6
Perimeter: 10

Instruction

You need to create a Rectangle class as below:

class Rectangle {
private:
	double length;
	double width;

public:
	Rectangle() {

	}

	Rectangle(double length, double width) {
		this->length = length;
		this->width = width;
	}

	double getLength() {
		return length;
	}

	void setLength(double length) {
		this->length = length;
	}

	double getWidth() {
		return width;
	}

	void setWidth(double width) {
		this->width = width;
	}

	double getArea() {
		return length * width;
	}

	double getPerimeter() {
		return (length + width) * 2;
	}
};