Design a class named Month. The class must have a private member of type int to
ID: 3763200 • Letter: D
Question
Design a class named Month. The class must have a private member of type int to hold the month number and a static member of type array of strings to hold the month names in the fashion of a lookup table. The class will have a default constructor that sets the month number to 1, as well as a constructor that accepts an int argument representing the month number. In addition, write the appropriate mutator functions to set the month based on month number and month name . Overload both the prefix and postfix versions of ++ and -- operators , such that they increment or decrement the month number respectively. Note: if month number is 12 when the increment operator is called, the month number will become 1. By the same token, if month number is 1 and the decrement operator is called, the month number becomes 12. Also overload the > operators such that the > operator allows the user to input a month number. Write a test program that would demonstrate the Month class . The program would allow the user input two month numbers and display the next 8 months and the previous 8 months (including the month that the user entered). You may assume the user will always input an integer between 1 and 12.
Explanation / Answer
If you have any further queries, just get back to me.
#include <iostream>
using namespace std;
class Month
{
private:
int month; //private integer variable month.
static const string monthName[13]; //Static array declaration.
public:
Month() //Default constructor.
{
month = 1;
}
Month(int m) //Constructor with argument.
{
this->setMonth(m);
}
void setMonth(int m) //Sets the month.
{
month = m;
}
string getMonth() //Gets the month name.
{
return monthName[month];
}
void operator++() //Overloading the ++ operator.
{
month++;
if(month > 12)
month = 1;
}
void operator--() //Overloading the -- operator.
{
--month;
if(month < 1)
month = 12;
}
void operator>(int m) //Overloading the > operator.
{
month = m;
}
};
const string Month::monthName[] = {"", "January", "February", "March", "April", "May",
"June", "July", "August", "September", "October",
"November", "December"};
int main()
{
Month m1;
int m;
cout<<"Enter the month number: "; //Reads the month.
cin>>m;
m1>m; //Assigns month value m to the object.
cout<<"The next 8 months from now, including this month is: "<<endl; //Prints the next 8 months.
for(int i = 0; i < 8; i++)
{
cout<<m1.getMonth()<<endl;
++m1;
}
cout<<"Enter the month number: "; //Reads the month
cin>>m;
m1>m; //Assigns month value m to the object.
cout<<"The previous 8 months from now, including this month is: "<<endl; //Prints the previous 8 months.
for(int i = 0; i < 8; i++)
{
cout<<m1.getMonth()<<endl;
--m1;
}
}
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.