3

I wrote the following code:

#include<iostream>
using namespace std;

class foo {
private:    
    int i;
public:
    foo(): i(1) { }
    friend int func1(int i) {
        return 0;
    }
    friend int func2(foo &f) {
        return f.i;
    }
};

int main()
{
    foo f;
    cout << func2(f) << endl;
    cout << func1(1) << endl;
    return 0;
}

But it cannot compile with the following errors:

ss.cpp: In function ‘int main()’:
ss.cpp:28:17: error: ‘func1’ was not declared in this scope

When I deleted this line:

cout << func1(1) << endl;

It compiled successfully

Does that means if I want to define a friend function in a class and call it in global namespace, It must have some relationship with the class ? If so, what's the rule in detail ?

My compiler is g++-4.7.2

Fei Jiang
  • 330
  • 1
  • 6
  • 1
    You can declare friend functions without constraints. What you have here is ADL failure. – Andrei Tita Jan 05 '13 at 09:47
  • You might find this helpful: http://stackoverflow.com/questions/7785886/access-friend-function-defined-in-class – chris Jan 05 '13 at 09:47

1 Answers1

5

You seem to have found the rule yourself. To be found, the function must have a parameter of the class type.

See Argument Dependent Lookup at Wikipedia.

Bo Persson
  • 90,663
  • 31
  • 146
  • 203