-
Class Help
Can anyone tell me why I get the following errors, it is complaing about accessing a private variable for a function that I have defined as a freind function to the class:
Code:
example.cpp: In function `void display(ostream &, Time &)':
example.cpp:6: `int Time::hour' is private
example.cpp:21: within this context
example.cpp:6: `int Time::mins' is private
example.cpp:21: within this context
example.cpp:6: `int Time::secs' is private
example.cpp:22: within this context
When compling this program:
Code:
#include <iostream>
using namespace std;
class Time
{
private: int hour, mins, secs;
public: Time( int h = 12, int m = 0, int s = 0)
{
hour = h; mins = m; secs = s;
}
void enterTime()
{
cout << "Enter the hour, minutes and seconds:\n";
cin >> hour >> mins >> secs;
}
friend void display( ostream & out, const Time & obj );
};
void display( ostream & out, Time & obj )
{
out << obj.hour << ":" << obj.mins << ":"
<< obj.secs << ' ';
}
void main()
{
Time T1, T2(4, 30), T3(3);
T1.enterTime();
cout << "Here's T1, T2, and T3:\n";
display(cout, T1); display(cout, T2); display(cout,T3);
}
I am using g++, if that makes a difference.
-
Here yah go...
here yah go mate..
Code:
friend void display( ostream & out, const Time & obj );
where u have const it is telling the compiler not to change any of the private data members of Time class.....
doesn't appear that you are doing that.. but it appears ostream is trying to do stuff to hours, mins, and seconds...
so an easy solution appears to be to use this code..
Code:
friend void display( ostream & out, Time & obj );
well by golly.. i believe i have helped two people today... my good deeds for the year have been completed... i should be given an award or something... (cash is also acceptable..)
-
Well Hey that worked, it was actually just an example my teacher gave us, I just wanted to see if it actually worked.... Everything seemed logical, but now I definately have a better understanding of what was going on....
Thanks.