Reputation: 1506
what's wrong with this code?
class matrix{
private:
friend transpose(const matrix&);
friend class invert;
public: //...
};
matrix (*p)(const matrix&)=&transpose; //error: no transpose() in scope.
what does the statement means "a friend declaration does not introduce a name into enclosing scope".This problem does not occur when friend keyword is removed
Upvotes: 1
Views: 1636
Reputation: 511
Friend functions are functions that are not members of a class but they still have access to the private members of the class.
I should point out that a friend function declaration
may be placed in either the private section or the public section,
but it will be a public function in either case, so it is clearer to
list it in the public section.
class MyClass { private: int data; public: MyClass(int value); friend void myFriend(MyClass *myObject); }; void myFriend(MyClass *myObject) { cout << myObject->data<< endl; } MyClass::MyClass(int value) { data = value*2; } int main() { MyClass myObject(3); myFriend(&myObject); }
So, you need to define the friend function after you declare it.
Upvotes: 0
Reputation: 24341
The difference between the declaration of transpose() as a friend and without the friend declaration is that if you declare "friend transpose()" all you are doing is telling the compiler that a function friend with the signature shown in the friend declaration can have access to the private members of an object of type matrix. It does not declare a function transpose() with this signature - you still have to do this outside the scope of the matrix class.
If you remove the 'friend' keyword, you are declaring a member function transpose() inside the class matrix, so the compiler actually has seen a function it can take the address of.
Upvotes: 1
Reputation: 131789
§7.3.1.2 [namespace.memdef] p3
[...] If a
friend
declaration in a nonlocal class first declares a class or function the friend class or function is a member of the innermost enclosing namespace. The name of the friend is not found by unqualified lookup or by qualified lookup until a matching declaration is provided in that namespace scope (either before or after the class definition granting friendship). [...]
See also this question of mine.
Upvotes: 1