1

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

amit
  • 175,853
  • 27
  • 231
  • 333
T.J.
  • 1,466
  • 3
  • 19
  • 35

3 Answers3

1

§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.

Community
  • 1
  • 1
Xeo
  • 129,499
  • 52
  • 291
  • 397
  • if we only declare not define a friend function in enclosing scope then it would work or not? what if we only declare it in enclosing scope and not declare it – T.J. Jan 18 '12 at 17:12
1

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.

Timo Geusch
  • 24,095
  • 5
  • 52
  • 70
0
  1. Friend functions are functions that are not members of a class but they still have access to the private members of the class.

  2. 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.

haberdar
  • 501
  • 5
  • 6