Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations Mike Lewis on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Overloading << in VC++

Status
Not open for further replies.

borgrulze

Programmer
Apr 4, 2002
11
0
0
IN
hi,
The following code just doesn;t work even though it is correct. It gives an error can't access mo even though the it is accessed within the friend function. Try it!. Please let me know what's worng.

#include <iostream>
using namespace std;

class Date
{
int mo, da, yr;
public:
Date( int m, int d, int y )
{
mo = m; da = d; yr = y;
}
friend ostream& operator<< ( ostream& os, Date& dt );

};

friend ostream& operator<< ( ostream& os, Date& dt )
{
os << dt.mo << '/' << dt.da << '/' << dt.yr;
return os;
}

void main( )
{
Date dt( 5, 6, 92 );
cout << dt;
}
 
Hi Borg,

Hi Think Error is In Statement,

friend ostream& operator<< ( ostream& os, Date& dt )
{
os << dt.mo << '/' << dt.da << '/' << dt.yr;
return os;
}

it should be

ostream& operator<< ( ostream& os, Date& dt )
{
os << dt.mo << '/' << dt.da << '/' << dt.yr;
return os;
}
 
Even after removing the friend keyword it does not work check it out.
 
Try this:

#include <iostream>
using namespace std;

class Date
{
int mo, da, yr;
public:
Date( int m, int d, int y )
{
mo = m; da = d; yr = y;
}
friend ostream& operator<< ( ostream& os, Date& dt )
{
os << dt.mo << '/' << dt.da << '/' << dt.yr;
return os;
}
};

void main( )
{
Date dt( 5, 6, 92 );
cout << dt;
}
 
This isn't the cause of your problem, but the second operand of operator<< should really have type const Date &.
 
That's not it.
7496764 was right,you just have to remove the keyword &quot;friend&quot; from:

friend ostream& operator<< ( ostream& os, Date& dt )
{
os << dt.mo << '/' << dt.da << '/' << dt.yr;
return os;
}

and your code will compile without any error.
 
Actually there is a bug with MSVC++ with friend functions. The best way around it is to download the service pack, but that is overly large, so (if I can remember correctly) the seemingly odd way to fix it is to add in the following lines of code before the definition of the class Date:

class Date;
ostream& operator<< (ostream& os, const Date& dt);

This for some reason fixes the bug in MSVC++. But still, the best way is to download the service pack.
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top