Overloading operators

The program converts the day enter into month and day. The problem I have is trying to get the overloading operators to work, so far the operators aren't working. Any help with my operators would be helpful.

Last edited on
1
2
3
4
5
6
7
8
DayOfYear DayOfYear::operator++()
{
    int day;
    ++day;
    cout<< day;
    simplify();
    return *this;
}


I believe you are declaring an integer local to this method, incrementing its uninitialized value, couting it, and then returning. You are not editing any member variable. Remove "int day;" to make "++day" have an effect on the class object's variable instead.

Same goes for postfix and operator --.



I understand what you mean but after i made the change the cout<<day test isn't showing any value.
Where are you calling the overloaded operators?

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
	// ...
	int day;
	string month;

    do
    {
        cout << "\nEnter the day number and Enter 911 to stop the program";
        cout << endl << "Day Entered: ";
        cin >> day;

        if(day == 911)
        {
            cout << "The Program has Ended" << endl;
        }

	++day;
	// ... 


Note that you're not calling an overloaded operator here since day is only an integer variable and not a class object of DayOfYear.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
// ...
	int day;
	string month;

    do
    {
        cout << "\nEnter the day number and Enter 911 to stop the program";
        cout << endl << "Day Entered: ";
        cin >> day;

        if(day == 911)
        {
            cout << "The Program has Ended" << endl;
        }

	++dYear;
	// ...  


Ah, sorry I had the wrong idea of operators. So i changed ++day to ++dYear the class object and can see the operator running now. So is the operator ++ suppose to change 1 to 2? Cause its not doing that right now
The overloaded operator on the class does whatever you want it to do.

If you want to increment the integer day by 1:
1
2
3
4
5
6
7
DayOfYear &DayOfYear::operator++()
{
    ++day;
    cout << day;
    simplify();
    return *this;
}


Note the &, you'll return the same object instead of copying it.
The instructions for the operators are
++ 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 theyear, 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.

I added the &, the day inside the operator increases but the day in the main remains the same integer i put in.
Last edited on
That's because the day integer you have in main is in no way related to the object.
Topic archived. No new replies allowed.