Overload operator >>, passing one parameter to an object instead of 3

I have an object "d" of type Date. I am trying to use the overload operator to only accept one parameter from the user instead of the three that objects have. In other words, I want the program to be able to accept input from the user and be able to modify only the "month_" data item, and then pass that data item to "incMon ()" so that the month and year are consistent with what many months the user wants to increment the date using only the "month_" item.

How can I customize the overload operator and incMon () to allow this process?

This is what I have.

void Date::read(istream & is)
    {
        unsigned month;

        is >> month;

        month_ = month;

    }


    istream & operator>>(istream & is, Date & d)
    {
        d.read(is);
        return is;
    }

      

+3


source to share


3 answers


I am interpreting the original question as: "How do I make this core function work?"

Minimal intrusive way:



istream & operator>>(istream & is, Date & d)
{
   int num = 0;
   is >> num;
   d.incrementMonth(d, num);
   return is;
}

      

Although I want to emphasize that this solution results in some pretty unexpected code (reading an object and reading an int to grow).

+1


source


The overloaded input operator -> must be declared as friend:

friend istream & operator>>(istream & is, Date & d);

      

and is defined outside the class as shown below:



istream & operator>>(istream & is, Date & d)
{
   is >> d.month_; // input the month only
   d.day_ = d.year_ = 0; 
   return is;
}

      

To assign values ​​for the day and year, assign some valid defaults to make the date object complete by accepting input Your date object will now accept input from a single value as desired. Good?

+1


source


What about

int increment;
cout << "Enter month increment (0 to exit): " << endl;
cin >> increment;
if (increment == 0) {
   // your special exit stuff
}
d.incrementMonth(increment);

      

This way you can:

  • Exit to 0 as your typed comment suggests
  • Eliminate the first parameter of the incrementMonth method. (Use a variable instead this

    .)
+1


source







All Articles