misc.cpp 1.4 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667
  1. #include <iostream>
  2. #include <stdio.h>
  3. using namespace std;
  4. class Date
  5. {
  6. public:
  7. Date() : day(1), month(1), year(2000) {counter++;}
  8. Date(int d, int m, int y) : day(d), month(m), year(y) {counter++;}
  9. ~Date() {counter--;}
  10. private:
  11. int day;
  12. int month;
  13. int year;
  14. static int counter; // Статические переменные инициализируются вне класса
  15. public:
  16. static int getCounter() {
  17. return counter;
  18. }
  19. public:
  20. void print() { // Константный метод не изменяет состояние объекта
  21. cout << day << "." << month << "." << year << endl;
  22. }
  23. int getDay() const {
  24. return day;
  25. }
  26. Date& setDay(int day) {
  27. this->day = day;
  28. return *this;
  29. }
  30. Date& setMonth(int month) {
  31. this->month = month;
  32. return *this;
  33. }
  34. void setDate(int d, int m, int y); // boid setDate(Date* const this, int d, int m, int y)
  35. };
  36. // Статические переменные инициализируются вне класса
  37. int Date::counter = 0;
  38. void Date::setDate(int d, int m, int y)
  39. {
  40. day = d;
  41. month = m;
  42. year = y;
  43. }
  44. int main()
  45. {
  46. //const Date date(17, 9, 2023); // Для const объектов можно вызывать только const-методы
  47. Date date;
  48. Date date_2;
  49. date.setDate(18, 9, 2023); // setDate(&date, 18, 9, 2023)
  50. date.print();
  51. date.setDay(3).setMonth(9);
  52. date.print();
  53. cout << "Objects number: " << Date::getCounter() << endl;
  54. }