私は以下のように名前空間内にクラスを持っています。コンパイルで TEST.Hエラー: 'member'はこのコンテキスト内でプライベートです - 名前空間
#include <iostream>
using std::cout;
namespace n1
{
class myClass;
}
class n1::myClass
{
public:
myClass(int na, int nb):a(na), b(nb){}
private:
int a;
int b;
friend std::ostream& operator << (std::ostream & stream, const n1::myClass& cls);
};
TEST.CPP
#include "test.h"
std::ostream& operator << (std::ostream & str, const n1::myClass& cls)
{
str << cls.a << " " << cls.b << std::endl;
}
、私は次のエラーを取得しています。
test.h: In function ‘std::ostream& operator<<(std::ostream&, const n1::myClass&)’:
test.h:13:6: error: ‘int n1::myClass::a’ is private
test.cpp:5:13: error: within this context
test.h:14:6: error: ‘int n1::myClass::b’ is private
test.cpp:5:29: error: within this context
どうすればエラーが発生しますか?あなたはmyClass
は、名前空間n1
で友人を持っていますが、実際にはグローバル名前空間にオペレータを宣言すると約束しましたので
namespace n1
{
std::ostream& operator << (std::ostream & str, const myClass& cls)
{
str << cls.a << " " << cls.b << std::endl;
}
}
:あなたはmyClass
が定義された名前空間内のオペレータ<<
を定義することができます
おそらくストリームの名前ですが、strとヘッダファイルストリームにcppを書きました。また、あなたはcppに友達を入れようとしましたか? – Serizba
@Serizba:いいえ、 'stream'という名前を削除して、型だけで定義を残すこともできます。 – deepmax