Can't access a static private data member from a friend function?

J

JustSomeGuy

I have a class with a private data member and I want to access it
from a friend function, but Visual Studio 2003 .NET won't let me.

class MyClass
{
private:
static int level;
public:
friend ostream & operator<<(ostream & x, const MyClass & c);
}

int MyClass::level = 0;

ostream & operator<<(ostream & x, const MyClass & c)
{
O << c.level;
}
 
J

Jonathan Turkanis

JustSomeGuy said:
I have a class with a private data member and I want to access it
from a friend function, but Visual Studio 2003 .NET won't let me.
class MyClass
{
private:
static int level;
public:
friend ostream & operator<<(ostream & x, const MyClass & c);
}

int MyClass::level = 0;

ostream & operator<<(ostream & x, const MyClass & c)
{
O << c.level;
}

Post some code that has some hope of compiling. Among other things, you've
omitted the semicolon at the end of the definition of MyClass, you've used an
undeclared variable O in the implementation of operator<<, and the function
doesn't return a value.

Jonathan
 
S

Sumit Rajan

JustSomeGuy said:
I have a class with a private data member and I want to access it
from a friend function, but Visual Studio 2003 .NET won't let me.

#include <iostream>

using namespace std;

class MyClass
{
private:
static int level;
public:
friend ostream & operator<<(ostream & x, const MyClass & c);
}

missing ;
int MyClass::level = 0;

ostream & operator<<(ostream & x, const MyClass & c)
{
O << c.level;

x << c.level; //or "x << MyClass::level;"
return x; // undefined behaviour if you forget to return x

Regards,
Sumit.
 
D

Daniel Mitchell

JustSomeGuy said:
I have a class with a private data member and I want to access it
from a friend function, but Visual Studio 2003 .NET won't let me.

class MyClass
{
private:
static int level;
public:
friend ostream & operator<<(ostream & x, const MyClass & c);
}

int MyClass::level = 0;

ostream & operator<<(ostream & x, const MyClass & c)
{
O << c.level;
}

ostream& operator<<( ostream& x, const MyClass& c )
{ return x << c::level; }
 

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

No members online now.

Forum statistics

Threads
473,969
Messages
2,570,161
Members
46,705
Latest member
Stefkari24

Latest Threads

Top