friend int pqr(abc);
宣言は大丈夫です。abc
関数でパラメーターの型として使用する前に型が定義されていないため、機能しませんpqr()
。関数の前に定義します。
#include<iostream>
// By the way, "using namespace std" can cause ambiguities.
// See http://www.parashift.com/c++-faq-lite/coding-standards.html#faq-27.5
using namespace std;
// Class defined outside the pqr() function.
class abc
{
int x;
public:
int xyz()
{
return x=4;
}
friend int pqr(abc);
};
// At this point, the compiler knows what abc is.
int pqr(abc t)
{
t.xyz();
return t.x;
}
int main()
{
abc t;
cout<<"Return "<<pqr(t)<<endl;
}
ローカル クラスを使用したいのはわかっていますが、設定したものが機能しません。ローカル クラスは、それが定義されている関数の内部でのみ表示されます。関数のabc
外部で のインスタンスを使用する場合は、関数の外部でクラスpqr()
を定義する必要があります。abc
ただし、abc
クラスが関数内でのみ使用されることがわかっている場合pqr()
は、ローカル クラスを使用できます。friend
ただし、この場合、宣言を少し修正する必要があります。
#include<iostream>
// By the way, "using namespace std" can cause ambiguities.
// See http://www.parashift.com/c++-faq-lite/coding-standards.html#faq-27.5
using namespace std;
// pqr() function defined at global scope
int pqr()
{
// This class visible only within the pqr() function,
// because it is a local class.
class abc
{
int x;
public:
int xyz()
{
return x=4;
}
// Refer to the pqr() function defined at global scope
friend int ::pqr(); // <-- Note :: operator
} t;
t.xyz();
return t.x;
}
int main()
{
cout<<"Return "<<pqr()<<endl;
}
これは、Visual C++ (コンパイラのバージョン 15.00.30729.01) で警告なしでコンパイルされます。