3

以下のコードをコンパイルしようとすると、以下のエラーが発生します。

Error: main.cpp: In function "int main()":
       main.cpp:6: error: "display" was not declared in this scope

test1.h

#include<iostream.h>
class Test
{
  public:
    friend int display();
};

test1.cpp:

#include<iostream.h>
int  display()
{
    cout<<"Hello:In test.cc"<< endl;
    return 0;
}

main.cpp

#include<iostream.h>
#include<test1.h>
int main()
{
 display();
 return 0;
}

奇妙なことは、UNIX で正常にコンパイルできることです。gcc および g++ コンパイラを使用しています

4

2 に答える 2

3

関数をフレンドとして宣言する前に、関数の宣言を提供する必要があります。
標準では、friend としての宣言は、実際の関数宣言とは見なされません。

C++11 標準 §7.3.1.2 [namespace.memdef]:
パラ 3:

[...]friend非ローカル クラスの宣言が最初にクラスまたは関数を宣言する場合、フレンド クラスまたは関数は、最も内側にある名前空間のメンバーです。フレンドの名前は、その名前空間スコープで一致する宣言が提供されるまで(クラス定義がフレンドシップを付与する前または後に)、非修飾ルックアップまたは修飾ルックアップによって検出されません。[...]

#include<iostream.h>
class Test
{
  public:
    friend int display();  <------------- Only a friend declaration not actual declaration
};

必要なもの:

#include<iostream.h>
int display();            <------- Actual declaration
class Test
{
  public:
    friend int display();     <------- Friend declaration 
};
于 2013-03-29T06:38:16.723 に答える
2

面白い。inの宣言は g++ の実際の関数宣言としてカウントされるfriendようです。display()test1.h

標準が実際にこれを強制しているとは思わないので、おそらく in の適切な宣言を追加したいと思うでしょdisplay()test1.h:

#include <iostream>

int display();

class Test
{
public:
    friend int display();
};
于 2013-03-29T06:34:27.623 に答える