c++ - 如何将全局范围函数声明为命名空间类的 friend ?

标签 c++ namespaces friend friend-function

以下代码定义了 class Foonamespace 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/

相关文章:

c++ - 大数排列 nPr 的最佳程序

c++ - 在命名空间 'names'::std::vs std::

c++ - 限定名称和使用声明的 clang 错误消息

c++ - 使用 Doxygen 记录命名空间

c++ - 具有特定模板类 : "template<ANY...> friend class A;" 的 friend

c++ - 指针有问题?

c++ - getline 项目返回空变量

c++ - 在测试中使用友元

c++ - 如何仅在一个函数的参数上应用类型映射?

c++ - 如何将模板类与其 friend 模板类分离到不同的头文件中?