以下代码定义了 class Foo
在 namespace Namespace
.
// main.cpp
#include <csignal>
namespace Namespace
{
class Foo
{
private:
void doSomething() {};
friend void func( union sigval );
};
}
static Namespace::Foo foo;
void func( union sigval sv ) {
(void)sv;
foo.doSomething();
}
我想做 void func( union sigval )
此类的 friend ,以便它可以调用私有(private)函数。 执行此操作的正确语法是什么?以上失败并出现以下错误 :$ g++ --version && g++ -g ./main.cpp
g++ (Debian 6.3.0-18+deb9u1) 6.3.0 20170516
Copyright (C) 2016 Free Software Foundation, Inc.
This is free software; see the source for copying conditions. There is NO
warranty; not even for MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
./main.cpp: In function ‘void func(sigval)’:
./main.cpp:22:19: error: ‘void Namespace::Foo::doSomething()’ is private within this context
foo.doSomething();
^
./main.cpp:11:8: note: declared private here
void doSomething() {};
^~~~~~~~~~~
这个变化...
friend void ::func( union sigval );
...导致此错误:$ g++ -g main.cpp
main.cpp:13:34: error: ‘void func(sigval)’ should have been declared inside ‘::’
friend void ::func( union sigval );
^
最佳答案
您只需使用 ::
即可引用全局范围.所以你的 friend 声明可以是:
friend void ::func( union sigval );
但是不要忘记在类中引用它之前转发声明该函数!因此,在全局范围内,您将需要:
void func( union sigval );
在类声明之前。编译示例:https://ideone.com/hDHDJ8
关于c++ - 如何将全局范围函数声明为命名空间类的 friend ?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/64794265/