是否可以将友元函数声明为静态函数?

2022-01-05 00:00:00 static c++ friend

这里是一些编译和工作正常的 C++ 示例代码:

Here is some C++ example code that compiles and works fine:

class A
{
public:
   A() {/* empty */}

private:
   friend void IncrementValue(A &);
   int value;
};

void IncrementValue(A & a)
{
   a.value++;
}   

int main(int, char **)
{
   A a;
   IncrementValue(a);
   return 0;
}

然而,我想要做的是将 IncrementValue() 声明为静态,以便无法从另一个编译单元看到或调用它:

What I would like to do, however, is declare IncrementValue() as static, so that it can't be seen or called from another compilation unit:

static void IncrementValue(A & a)
{
    a.value++;
}

然而,这样做会给我一个编译错误:

Doing that, however, gives me a compile error:

temp.cpp: In function ‘void IncrementValue(A&)’:
temp.cpp:12: error: ‘void IncrementValue(A&)’ was declared ‘extern’ and later ‘static’
temp.cpp:8: error: previous declaration of ‘void IncrementValue(A&)’

... 将友元声明更改为匹配也无济于事:

... and changing the friend declaration to match doesn't help:

friend static void IncrementValue(A &);

... 因为它给出了这个错误:

... as it gives this error:

temp.cpp:8: error: storage class specifiers invalid in friend function declarations

我的问题是,在 C++ 中有没有什么方法可以有一个(非方法)友元函数被声明为静态的?

My question is, is there any way in C++ to have a (non-method) friend function that is declared static?

推荐答案

引用 N3691 - §11.3/4 [class.friend]

Quoting N3691 - §11.3/4 [class.friend]

首先在友元声明中声明的函数具有外部链接(3.5).否则,该函数保留其先前的链接(7.1.1).

A function first declared in a friend declaration has external linkage (3.5). Otherwise, the function retains its previous linkage (7.1.1).

因此您需要在将函数声明为 friend 之前将其声明为 static .这可以通过在 A 的定义上方添加以下声明来实现.

So you need to declare the function as static prior to declaring it as a friend. This can be done by adding the following declarations above the definition of A.

class A;  // forward declaration, required for following declaration
static void IncrementValue(A&); // the friend declaration will retain static linkage

相关文章