|
-
May 7th, 2002, 12:13 PM
#1
overloading ostream for a class
I have many values stored in a class under the protected: heading. In the public section of the function I have a ostream friend ( ostream & operator << (ostream &o, const class c) ). In the ostream friend I tried o << on the values stored in the class ( o << c.value; ). I get the compiler error 'value' : cannot access protected member declarded in class.
First off why doesn't this work, shouldn't the program make a copy of the class in the varible c, I thought when you passed a class by value it called the default constructor and copy constructor to make a copy of your class. Why can't the function who owns the class varible not access the protected memebers?
I'm not going to have to make a public function to return all the values from the protected section, am I? That would seriously suck!
I know there must be an easier way, some one care to enlighten the dim-witted
NOMAD
-
May 10th, 2002, 05:08 AM
#2
Only functions of the class itself and derived classes can access protected members. There is no "owner of variable" concept in C++.
First, you should make the prototype of the overload
ostream & operator << (ostream &os, const myclass &c);
because you don't want a copy to be made - it takes too long and does no good.
To grant this function access to private and protected class members, you must add this line to the class declaration:
friend ostream & operator << (ostream &, const myclass &);
All the buzzt
 CornedBee
"Writing specifications is like writing a novel. Writing code is like writing poetry."
- Anonymous, published by Raymond Chen
Don't PM me with your problems, I scan most of the forums daily. If you do PM me, I will not answer your question.
Posting Permissions
- You may not post new threads
- You may not post replies
- You may not post attachments
- You may not edit your posts
-
Forum Rules
|
Click Here to Expand Forum to Full Width
|