English 中文(简体)
friend function declared inside befriended class, GCC does not compile
原标题:

I ve got following code:

File: Foo.h

class Foo {
    friend void Bar();
};

File: Foo.cpp

void Bar() {};

File Test.cpp

#include "Foo.h"

int main(void) {
    Bar();
    return 0;
}

VS2008 compiles this without any error or warning. G++ 4.3.4 reports:

test.cpp: In function ‘int main()’:
test.cpp:8: error: ‘Bar’ was not declared in this scope

Why?

最佳回答

I found this question in the "unanswered" section, but the comments to the previous incorrect answer do constitute a correct answer. Therefore here is a community wiki response with that content.

Summary: GCC appears to be rejecting good code.

case when a friend function is defined (not only declared) inside class is covered by 11.4.5 ("A function can be defined in a friend declaration of a class if and only if the class is a non-local class, the function name is unqualified, and the function has namespace scope" -- your example fulfils these requirements). I guess that standard does allow declaration ("prototype") of a friend function inside class. It is the error g++ is generating which bothers me. – liori Nov 22 at 20:35

Also 11.4.3: "A function first declared in a friend declaration has external linkage (3.5). Otherwise, the function retains its previous linkage (7.1.1)." I think that seals the deal. – Potatoswatter 0 secs ago [delete this comment]

问题回答

A friend declaration doesn t count as a prototype. You also need to need a separate prototype:

// File: Foo.h

void Bar();

class Foo {
    friend void Bar();
};




相关问题
Benefits of declaring a function as "inline"?

Every time I read about the "inline" declaration in C it is mentioned that it is only a hint to the compiler (i.e. it does not have to obey it). Is there any benefit to adding it then, or should I ...

热门标签