38

コンパイルして正常に動作する C++ のサンプル コードを次に示します。

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() を static として宣言して、別のコンパイル ユニットから参照または呼び出しできないようにすることをお勧めします。

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

ただし、それを行うと、コンパイルエラーが発生します。

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&)’

...そして、フレンド宣言を一致するように変更しても役に立ちません:

friend static void IncrementValue(A &);

...このエラーが発生するため:

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

私の質問は、静的と宣言された (非メソッド) フレンド関数を C++ で使用する方法はありますか?

4

3 に答える 3

17

もちろん。エラー メッセージの 2 行目を注意深く読んでexternください。したがって、フレンド宣言の前に static を宣言するだけです。 static

class A;
static void IncrementValue(A&);

class A {
    // class definition, including friend declaration
};

static void IncrementValue(A&) {
    // code here, of course
}
于 2013-11-07T20:04:28.560 に答える