1

私は以下のように名前空間内にクラスを持っています。コンパイルで 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が定義された名前空間内のオペレータ<<を定義することができます

+0

おそらくストリームの名前ですが、strとヘッダファイルストリームにcppを書きました。また、あなたはcppに友達を入れようとしましたか? – Serizba

+0

@Serizba:いいえ、 'stream'という名前を削除して、型だけで定義を残すこともできます。 – deepmax

答えて

2

+0

salam、1 soal dashtam、年齢betonid konakam konid mamnon misham.manzor az 'このバッジを達成するには、少なくとも200の非コミュニティWikiの回答に合計点数1000を設定する必要があります。 'chie?be chesoal haie' non-community wiki 'migan.khaheshan javab bede.harchi serch kardam motavajeh nashodam.Email:[email protected] – Ehsan

+0

@ehsan:[this](https://meta.stackexchange.com/tags/community-wiki/info)を読んでください。 [this](https://stackoverflow.com/questions/1642028/what-is-the-operator-in-c)がその例です。あなたは質問の右下にフレーズ 'community wiki'を見ることができます。 – deepmax

関連する問題