사용자 정의 네임 스페이스에 속하는 클래스에 < < 연산자를 오버로드하려고합니다. 흥미로운 점은 만약 네임 스페이스를 모두 없애면 프로그램이 문제없이 컴파일되고 실행된다는 것입니다. 그러나 클래스가 네임 스페이스에 상주한다는 사실은 어떻게 든 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 :
#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 –