问题描述
以下是一些可以编译并正常工作的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]
因此您需要将函数声明为在之前将其声明为
。这可以通过在朋友
的静态 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
这篇关于是否可以将一个朋友函数声明为静态函数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!