confusion about friend declarator

M

Mark

the following is an example of code that won't compile.
(I've reproduced the problem in a simplistic format )

....
#include <iostream>
using namespace std;

class MyClass
{
public:
unsigned int myint;

ostream& operator<<( ostream& o,MyClass& myclass)
{
return o;
}

};

I get : error C2804: binary 'operator <<' has too many parameters

However I can fix this if I declare it as

friend ostream& operator<<( ostream& o,MyClass& myclass)
{
return o;
}

Why? The function is doing nothing that requires access to the internals
of the class ( there are no internals !! )
 
J

Jonathan Turkanis

Mark said:
the following is an example of code that won't compile.
(I've reproduced the problem in a simplistic format )

...
#include <iostream>
using namespace std;

class MyClass
{
public:
unsigned int myint;

ostream& operator<<( ostream& o,MyClass& myclass)
{
return o;
}

};

I get : error C2804: binary 'operator <<' has too many parameters

However I can fix this if I declare it as

friend ostream& operator<<( ostream& o,MyClass& myclass)
{
return o;
}

Why? The function is doing nothing that requires access to the
internals of the class ( there are no internals !! )

The sedond declaration declares a non-member function in the enclosing scope.

Jonathan
 
R

Rolf Magnus

Mark said:
the following is an example of code that won't compile.
(I've reproduced the problem in a simplistic format )

...
#include <iostream>
using namespace std;

class MyClass
{
public:
unsigned int myint;

ostream& operator<<( ostream& o,MyClass& myclass)

Here you define it as member operator with two parameters. But the member
operator must only have one. It takes the this-object as left-hand
argument.
{
return o;
}

};

I get : error C2804: binary 'operator <<' has too many parameters

However I can fix this if I declare it as

friend ostream& operator<<( ostream& o,MyClass& myclass)
{
return o;
}

Why ?

Now it's a non-member operator, which needs two parameters. That one is just
a shorter way to write:

class MyClass
{
//...
friend ostream& operator<<( ostream& o,MyClass& myclass);
};

ostream& operator<<( ostream& o,MyClass& myclass)
{
return o;
}

The function is doing nothing that requires access to the internals
of the class ( there are no internals !! )

For the declaration of a function, it doesn't matter what that function
does.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,774
Messages
2,569,599
Members
45,175
Latest member
Vinay Kumar_ Nevatia
Top