Reputation: 7164
class Class1{
public:
Class1(Class2 * a, int b );
~Class1();
friend ostream& operator<< (ostream& x, const Class1& c1);
private:
int b;
Class2 * a;
};
ostream& operator<< (ostream& x, const Class1& c1)
{
stream<<"("<<c1.a->label<<","<<c1.b<<")"<<endl;
return x;
}
class Class2
{
public :
Class2 (string label);
~Class2();
string getLabel()
{
return label;
}
private:
string label;
vector<Class1 *> c1vector;
};
I'm trying to print the label and b of an edge, but it says the label is private. Can you tell me what I'm doing wrong? Thanks.
Upvotes: 0
Views: 57
Reputation: 12907
Well, you are trying to access a private member of Class2 directly, and the private property is actually what prevents you from doing this. (And the fact that you qualified operator<<
friend in Class1 doesn't change anything, label
is a private member of Class2).
Either make the member public (not recommended) or provide a public member function that returns the value of this member.
Upvotes: 1
Reputation: 23624
One issue is that: label
is private in Class2
, you cannot directly access it inside Class1
via an instance of Class2
, which is a
in this case. You may need to provide getters
inside Class2
.
class Class2
{
public :
string getLable()
{
return label;
}
private:
string label;
};//^^other members skipped for clearance purpose
Upvotes: 1
Reputation: 96233
label
is private within Class2
so it cannot be access through Class
or your operator<<
insertion function. The simplest solution is to provide a public const get_label
function in Class2
to access the label string.
A more in depth approach is to give Class2
its own print mechanism (either through a print/display/show function, or with its own operator<<
that can be used to show the label.
Upvotes: 1
Reputation: 7072
You have to write in Class2 friend ostream& operator<< (ostream& x, const Class1& c1);
, because only Class 1 is its friends but label if a private attibute of class2
Upvotes: 1