0

The program compiles but it only shows the addresses of myDate.year not the year that I input.

#include <iostream>

using namespace std;

 class Date
 {
	 friend ostream &operator<<( ostream &, const Date & );
	 friend istream &operator>>( istream &, const Date & );
private:
      int day, month, year;
}; 

istream &operator>>( istream &in, const Date &myDate)
{
    int d, m, y; 
    cout << "Enter three integers for day, month, year: ";
    in >> d >> m >> y; 
    return in;
}

ostream &operator<<( ostream & out, const Date &myDate)// removed friend 
{
      out << myDate.day << "/" << myDate.month << "/" 
	  << myDate.year << endl; 
	  return out;
}

int main()
{
	Date lastYear;
	cin >> lastYear;
	cout << lastYear;
return 0;
}
3
Contributors
2
Replies
3
Views
8 Years
Discussion Span
Last Post by BevoX
0

You aren't changing the values of the myDate object when you get input. You're asking for the values and then ignoring them.

0

Try with this.

// change this in your class declaration
friend istream& operator >> ( istream &, Date & );

istream& operator >> ( istream &in, Date &myDate )
{
	cout << "Enter three integers for day, month, year: ";
	in >> myDate.day >> myDate.month >> myDate.year;
	return in;
}

You should write your own constructor and a destructor, do not bother with the default ones. Try to sepearate data as much as you can. Making functions friend with your class will work, but in my opinion it is better to have your own "set" function, so you will be able to handle exceptions or invalid input data better with that way.

One more thing, when you take a reference as a constant, you basicly say, it is in "read-only mode", and you don't want that, when you actually want to give something a new value.

This topic has been dead for over six months. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.