ユーザー定義のネームスペースのクラスに< <演算子をオーバーロードしようとしています。興味深いのは、すべての名前空間のものを削除すると、プログラムは問題なくコンパイルされて実行されますが、クラスが名前空間に存在するという事実によって、ファイルA.cppのコンパイルプロセスが失敗し、 mクラスのプライベートデータにアクセスしようとしています(demo.cppはうまくコンパイルされます)。フレンド関数とネームスペース
demo.cpp:
#include <iostream>
#include "A.h"
int main() {
usr::A a(4);
std::cout << a << std::endl;
return 0;
}
ああ:
#ifndef A_H_
#define A_H_
#include <iostream>
namespace usr {
class A {
private:
int m_x;
public:
A(int x);
friend std::ostream& operator<<(std::ostream& os, const usr::A& a);
};
}
#endif // A_H_
A.cpp:
私の3ファイルのプログラムと私が手コンパイルエラーを見て、ください。#include "A.h"
usr::A::A(int x) : m_x(x) {}
std::ostream& operator<<(std::ostream& os, const usr::A& a) {
os << a.m_x;
return os;
}
エラー:
$ g++ -c A.cpp
In file included from A.cpp:1:0:
A.h: In function ‘std::ostream& operator<<(std::ostream&, const usr::A&)’:
A.h:10:17: error: ‘int usr::A::m_x’ is private
int m_x;
^
A.cpp:7:13: error: within this context
os << a.m_x;
^
関連する質問:http://stackoverflow.com/questions/30418270/clang-bug-namespaced-template-class-friend –