【发布时间】:2014-05-13 04:18:15
【问题描述】:
考虑以下代码:
#include <stdio.h>
class A
{
friend void foo(){ printf("%d\n",_a); }
public:
A(int);
private:
static const int _a=5;
};
class B
{
friend void foo(){ printf("%d\n",_a); }
private:
static const int _a=6;
};
int main()
{
foo();
}
编译后出现以下错误:
an_test.cpp:14:14: error: redefinition of ‘void foo()’
an_test.cpp:5:14: error: ‘void foo()’ previously defined here
an_test.cpp: In function ‘int main()’:
an_test.cpp:21:6: error: ‘foo’ was not declared in this scope
make: *** [an_test.o] Error 1
我认为用朋友说明符定义的函数是外部链接。那么为什么 an_test.cpp:21:6: error: ‘foo’ 没有在这个范围内声明呢?
【问题讨论】:
-
首先:不要在类中定义它们。使用
friend根本没有意义。 -
修复您的第一个错误
redefinition of ‘void foo()’,然后重试。foo不在范围内,因为编译器未能创建它。 -
@πάνταῥεῖ,在类中定义它仍然有意义,但不是没有任何参数。
-
内联好友功能只能使用ADL查找。