Reputation: 308
Please do not vote this down or mark this question as a duplicate for all of the answers that I have seen in other questions have not worked for me.
I created a class called contact that stores information about contacts. I was trying to implement an operator<< to output all information, so I had to make it a friend function. The problem with this is that I am unable to access any of the class's member functions. My code is as follows:
contact.h:
class contact {
long id;
string first;
string middle;
string last;
string company;
string home;
string office;
string email;
string mobile;
string street;
string city;
string state;
long zip;
string country;
vector<contact> affiliates;
public:
// output and input
friend ostream &operator<<(ostream &, const contact &);
};
contact.cpp:
...
ostream &operator<<(ostream &os, contact &rec) {
print(os, rec.id);
return os;
}
...
As you see, the function prototype is exactly the same, and I am not enclosing the class inside a namespace, which leaves no reason for the operator to be unable to access a member variable. Is this a problem with my prototype? Any help would be appreciated. Thanks.
Upvotes: 0
Views: 49
Reputation: 41301
The operator<<
declaration and definition are actually not the same. In the friend
declaration the second parameter is const contact &
, and in the definition it's just contact&
.
So the definition is actually unrelated to a friend
declaration in the class, and defines another function which is not a friend of contact
.
Upvotes: 3