Bài tập C++ OOP: tạo lớp Date để biểu diễn ngày giờ theo yêu cầu | Codelearn

  • TuanLQ7
  • Easy
  • 100 Points

Task

Create Date class in Data.cpp file with the following information:

Explanation:

  • day, month, year are attributes describing the day, month and year of the Date objective.
  • Date(day: int, month: int, year: int) is parameterized constructor used to initialize values to attributes.
  • setDate(day: int, month: int, year: int) method is used to change the values of attributes.
  • display() method displays the time information of object with the following format "dd/MM/yyyy". For example:
    • If day = 1, month = 7, year = 1997 and when we call the display() method, the text "01/07/1997" will display on the screen.
    • If day = 8, month = 12, year = 2003 and when we call the display() method, the text "08/12/2003" will display on the screen.
  • Other methods are setter and getter.
  • For simplicity, all values of the day, month and date of the Date class are considered to be valid.

A program to test the above Date class:

#include "Date.cpp"

using namespace std;

int main() {
	Date d(1, 1, 1997);
	d.display();
	d.setDate(12, 12, 2004);
	d.display();
	d.setMonth(3);
	d.display();	
	return 0;
}

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

01/01/1997
12/12/2004
12/03/2004

Instruction

You need to create a Date class as below:

#include<iostream>
#include<string>
using namespace std;

class Date {
private:
	int day;
	int month;
	int year;

public: Date(int day, int month, int year) {
	this->day = day;
	this->month = month;
	this->year = year;
}

	  void setDate(int day, int month, int year) {
		  this->day = day;
		  this->month = month;
		  this->year = year;
	  }

	  int getDay() {
		  return day;
	  }

	  void setDay(int day) {
		  this->day = day;
	  }

	  int getMonth() {
		  return month;
	  }

	  void setMonth(int month) {
		  this->month = month;
	  }

	  int getYear() {
		  return year;
	  }

	  void setYear(int year) {
		  this->year = year;
	  }

	  void display() {
		  string day = to_string(this->day);
		  string month = to_string(this->month);
		  string year = to_string(this->year);
		  if (day.length() == 1) {
			  day = "0" + day;
		  }
		  if (month.length() == 1) {
			  month = "0" + month;
		  }
		  cout << day + "/" + month + "/" + year << endl;
	  }
};