2010-07-14 5 views
4

다음과 같은 (컷 다운) 클래스 정의가 있으며 컴파일 오류가 있습니다.C++ friend 연산자 오버로드가 컴파일되지 않습니다.

#include <iostream> 
#include <string> 
class number 
{ 
    public: 
     friend std::ostream &operator << (std::ostream &s, const number &num); 
     friend std::string &operator << (std::string,  const number &num); 
     friend std::istream &operator >> (std::istream &s,  number &num); 
     friend std::string &operator >> (std::string,   number &num); 
    protected: 
    private: 
     void write (  std::ostream &output_target = std::cout) const; 
     void read (  std::istream &input_source = std::cin); 
     void to_string (  std::string &number_text) const; 
     void to_number (const std::string &number_text); 
}; 

std::istream & operator >> (std::istream &s,  number &num) 
{ 
    num.read (s); 
    return s; 
} 
std::string & operator >> (std::string &s, number &num) 
{ 
    num.to_number (s); 
    return s; 
} 
std::string & operator << (std::string &s, const number &num) 
{ 
    num.to_string (s); 
    return s; 
} 
std::ostream & operator << (std::ostream &s, const number &num) 
{ 
    num.write (s); 
    return s; 
} 

내가 컴파일 할 때, 나는 다음과 같은 오류를 얻을 ...

사람이 도움을 수
frag.cpp: In function ‘std::string& operator>>(std::string&, number&)’: 
frag.cpp:17: error: ‘void number::to_number(const std::string&)’ is private 
frag.cpp:27: error: within this context 
frag.cpp: In function ‘std::string& operator<<(std::string&, const number&)’: 
frag.cpp:16: error: ‘void number::to_string(std::string&) const’ is private 
frag.cpp:32: error: within this context 

; 특히 to_number와 to_string이 비공개로 생각되지만 읽거나 쓰는 것이 괜찮은 이유는 무엇입니까?

감사합니다.

+0

귀하의 도움에 감사드립니다. 머리/벽돌 벽 인터페이스에서 약간의 타박상이 발생했습니다. –

답변

5

함수 서명은 다르다 :

std::string & operator >> (std::string &s, number &num) ... 
std::string & operator << (std::string &s, const number &num) ... 

모두가 string& 기준 파라미터를 동시에

friend std::string &operator << (std::string,  const number &num); 
    friend std::string &operator >> (std::string,   number &num); 

는 값만큼 string 매개 변수로 선언되어있다. 따라서 실제로 구현하는 함수는 friend으로 선언 된 함수와 동일하지 않으므로 오류가 발생합니다.

답을 가지고 페테르 토록

friend std::string &operator << (std::string&,  const number &num); 
    friend std::string &operator >> (std::string&,   number &num); 
0

에 친구 선언을 변경하지만, 코드를 읽는에서 시도, 내가있을 수 있습니다 기대하는 구문 정크 너무 비슷 이름에 얽힌있어 어려움의 일부가되었습니다. 그렇게 했어.

s/std:://g 
s/to_string/wilma/g 
s/to_number/betty/g 

. 오류가 훨씬 눈에 띄었다.

+0

어쨌든 시도해 주셔서 감사합니다. 당신이 짐작 했겠지만, 이것은 좀 더 큰 범죄자로부터 잘라냅니다. –

관련 문제