简体   繁体   中英

How do I overload the pre and post increment operators for an object that is composed of a day and month to be printed as a std::string?

I am having some difficulty determining how to solve a part of a problem I am doing for my C++ course. This part requires the use of operator-overloading to correctly increment the days and the month. Maybe I am overlooking some very simple math, but somehow I am a bit confused as to how. Here is the code I have for my overloaded prefix and postfix operators for DayOfYear objects:

//Operators
DayOfYear operator++ () {return day++; }
DayOfYear operator++ (int) {return ++day;}
DayOfYear operator-- () {return day--;}
DayOfYear operator-- (int) {return --day;}

Obviously, this is redundant because day is an int so it only does what I could already do with ++ and -- to begin with. Below is the code for the DayOfYear class:

class DayOfYear {
    std::string month[12] = {"January", "February", "March",
                            "April", "May", "June", "July", "August", 
                            "September", "October", "November", "December"};

    //Each month's number of days, respectively
    int numDaysMonth[12] = {31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31};

    int day;

    //Convert day # to a string value
    static std::string dayToStr; 

    public:
        //First constructor
        DayOfYear (int day) {this -> day = day;} 

        //Second Constructor
        DayOfYear (std::string mth, int dayOfMonth) {
            //Make sure the dayOfMonth is valid
            if (dayOfMonth > 31 || dayOfMonth < 1) {
                if (mth == "February" && dayOfMonth > 28) {
                    std::cout << "Invalid day. February is assumed to be 28 
                    days for our purposes." << std::endl;
                 } else if ((mth == "April" || mth == "June" || mth == 
                    "September" || mth == "November") && dayOfMonth > 30) {
                    std::cout << "Invalid day. " << mth << " has only 30 
                    days." << std::endl;
                 } else {
                    std::cout << "Invalid day. The day should be >0 and <=31 
                    for most months." << std::endl;
                 }
           } else {
               day = dayOfMonth;
           }

       }

       //Accessors
       std::string getMonth (int mID) {return month[mID];}
       std::string getDay () {return dayToStr;}

       //Mutators
       void setDay (int d) {
           day = d;
       }

       //Operators
       DayOfYear operator++ () {return day++; }
       DayOfYear operator++ (int) {return ++day;}
       DayOfYear operator-- () {return day--;}
       DayOfYear operator-- (int) {return --day;}

       void print () {
           //TO-DO
       }
};

Right now, the code won't compile because the pieces aren't all there. However, I can read code fairly well I think, so I know my operators won't work. Somehow, I need to figure out how to make this code so that my main function (below) can compile and run correctly:

int main () {
    DayOfYear d (2);
    d.print ();
    d = 365;
    d.print ();
    d = 32;
    d.print ();

    d++;
    d.print ();

    d = 365;
    ++d;
    d.print ();
    d = 1;
    --d;
    d.print ();

    d = 32;
    d--;
    d.print ();

    DayOfYear e ("December", 31);
    e.print ();        

    return 0;
}

Specifically, as per the prof's specifications for this lab, I need to

  1. --prefix and postfix-- operators should modify the DayOfYear object(s) so that it represents the previous day. If the day is already the first day of the year, the new value of the object will represent the last day of the year.

  2. ++prefix and postfix++ increment operators. These operators should modify the DayOfYear object so that it represents the next day. If the day is already the end of the year, the new value of the object will represent the first day of the year.

So, I think my solution will require some use of % . Maybe I could overload it? I'm not sure. % can be overloaded according to the textbook.

I've been reading the textbook, and I think I know the basics of operator overloading in C++, but I think I am missing something simple or subtle. I've tried to look for something specific to this, but all I find is general information on operator overloading with structs and classes. I'm not sure what to do at the moment. I think my print () method is gonna be a challenge too, but the solution to this should make that last part of the assignment much easier.

Any guidance or assistance would be appreciated! Thanks.

EDIT: The professor explicitly stated in the problem requirements that I should assume that a year is 365 days.

I am taking the first C++ course offered at my college, so if there is a better way to do this with more advanced concepts, because they are irrelevant and I probably won't know what you are talking about. 因为它们无关紧要,而且我可能不知道您在说什么。

Write a class named DayOfYear that takes an integer representing a day of the year and translates it to a string consisting of the month followed by day of the month. 编写一个名为DayOfYear的类,该类采用表示一年中某一天的整数,并将其转换为包含月份和月份的字符串。 Examples: Day 2 => January 2, Day 32 => February 1, Day 365 => December 31. Assume 365 days in a year. The constructor for the class should take as parameter an integer representing the day of the year. The class should have a member function print() that prints the day in the month-day format like the examples above. Add a second constructor that takes two parameters: a string representing month and an integer (1-31) for the day of the month. The constructor should then initialize the integer member of the class to represent the day specified by the month and day of month parameters. Add the following overloaded operators: ++prefix and postfix increment operators. These operators should modify the DayOfYear object so that it represents the next day. If the day is already the end of the year, the new value of the object will represent the first day of the year. --prefix and postfix decrement operators. These operators should modify the DayOfYear object so that it represents the previous day. If the day is already the first day of the year, the new value of the object will represent the last day of the year.

My goal is to figure out these operators and the print () method mainly. I think I handled the other stuff okay, but this is giving me a snag.

All of your overloadings have problems. One thing they all shouldn't do is returning an int , and int day is an integer.


DayOfYear operator++ () {return day++; }

Here, the return type is DayOfYear , but it is supposed to be DayOfYear& .

DayOfYear&operator++() {
    ++day;
    return *this;
}

DayOfYear operator++ (int) {return ++day;}

Here, the return type is correct. You just have to return an object with the old value:

  DayOfYear operator++(int) {
    auto old_val = *this;
    ++*this;
    return old_val;
  }

Incorporated suggestions by @Deduplicator:

  • note the use of auto . It simplifies the method and improves readability
  • ++*this may be preferred to calling the operator manually since it is shorter and easier to type

Same applies to -- operators


Implementing a print function is indeed simple but you have some choices:

This one prints the date to standard output. The downside is that the only place it prints its output is standard output:

void print () {
    std::cout << getDay () << " / "  << getMonth() << std::endl;
}

You may send an std::ostream object and use it instead of std::cout :

void print (std::ostream& os) {
    os << getDay() << " / "  << getMonth() << std::endl;
}

Converting an int to an std::string is very conveniently possible with std::to_string . It is defined in header <string> , so make sure to include it:

std::string getDay () {
    return std::to_string(day);
}

Edit: As @Deduplicator pointed out, you may replace the print function with overloading << :

friend std::ostream& operator<<(std::ostream& os, DayOfYear x) {
    os << getDay () << " / "  << getMonth() << std::endl;
    return os;
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM