Bài tập C++ OOP: tạo lớp Point theo yêu cầu | Codelearn

  • TuanLQ7
  • Easy
  • 100 Points

Task

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

Explanation:

  • Point class stores the information of coordinates of a point in a two-dimensional coordinate system.
  • x, y are attributes that describe the abscissa and ordinate of the Point class.
  • Point() is the no-arg constructor.
  • Point(x: double, y: double) is the parameterized constructor used to initialize the values to x (abscissa) và y (ordinate).
  • setX(x: double), getX(), setY(y: double), getY() are the setter and getter.
  • setXY(x: double, y:double) is the atribute to change the values of x and y.
  • distance(x: double, y:double) method returns the distance between the current object and the point (x, y)
  • distance(another: Point) method returns the distance between the current object and another object (another is also an object of Point class).

A program to test Point class:

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

using namespace std;

int main() {
	Point p1(1.5, 6.7);
	Point p2(2.8, 3.2);
	cout << p1.distance(p2) << endl;
	cout << p1.distance(2.34, 7.8) << endl;
	return 0;
}

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

3.73363
1.38405

Instruction

You need to create a Point class as below:

#include<math.h>

class Point {
private:
	double x;
	double y;

public:
	Point() {
	}

	Point(double x, double y) {
		this->x = x;
		this->y = y;
	}

	double getX() {
		return x;
	}

	void setX(double x) {
		this->x = x;
	}

	double getY() {
		return y;
	}

	void setY(double y) {
		this->y = y;
	}

	void setXY(double x, double y) {
		this->x = x;
		this->y = y;
	}

	double distance(double x, double y) {
		return sqrt((this->x - x) * (this->x - x) + (this->y - y) * (this->y - y));
	}

	double distance(Point another) {
		return distance(another.getX(), another.getY());
	}
};