是否可以将一个朋友函数声明为静态函数? [英] Is it possible to declare a friend function as static?

查看:199
本文介绍了是否可以将一个朋友函数声明为静态函数?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

以下是一些可以编译并正常工作的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).

因此您需要将函数声明为在之前将其声明为朋友的静态。这可以通过在 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

这篇关于是否可以将一个朋友函数声明为静态函数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆