2011-09-19 11 views
1

변수가 개인용으로 사용되기 때문에 클래스의 개인 변수에 액세스 할 수없는 곳에서 내 operator<< 오버로드 문제가 있습니다. 컴파일러 오류.프렌드 연산자 << 오버로드 문제

std::ostream& operator << (std::ostream &out, const Library & l) 
^^^^^^^^^^^^^ 

당신은을 반환해야합니다 library.h

#ifndef LIBRARY_H 
#define LIBRARY_H 
#define BookNotFound 1 
#include "Book.h" 
#include <iostream> 
#include <cstdlib> 

using namespace std; 

namespace cs52{ 

    class Library{ 
    public: 
     Library(); 
     void newBook(string title, string author); 
     void checkout(string title, string author) {throw (BookNotFound);} 
     void returnBook(string title, string author) {throw (BookNotFound);} 
     friend Library operator << (Library& out, const Library & l); 

    private: 

     Book myBooks[ 20 ]; 
     int myNumberOfBooksSeenSoFar; 

    }; 
} 
#endif 

답변

5

당신의 << 운영자가이의 프로토 타입을 가져야 있습니다에

#include "library.h" 
#include "Book.h" 

using namespace cs52; 

Library::Library(){ 
    myNumberOfBooksSeenSoFar=0; 
} 
//skipping most of the functions here for space 

Library operator << (ostream &out, const Library & l){ 
    int i=myNumberOfBooksSeenSoFar; 
    while(i<=0) 
    { 
     cout<< "Book "; 
     cout<<i; 
     cout<< "in library is:"; 
     cout<< l.myBooks[i].getTitle(); 
     cout<< ", "; 
     cout<< l.myBooks[i].getAuthor(); 
    } 


    return (out); 
} 

그리고 함수 프로토 타입 및 개인 변수 : 이것은 내 현재 코드입니다 std::ostream 개체를 참조하면 스트림 작업을 연결할 수 있습니다.

Library 클래스에서 friend로 선언하는 경우 오버로드 된 함수에서 Library 클래스의 모든 구성원 (비공개/보호 된 멤버)에 액세스 할 수 있어야합니다.

friend Library operator << (Library& out, const Library & l); 
          ^^^^^^^^^^^^ 

당신은 프로토 타입으로 연산자 함수를 정의 : 나는 당신의 코드를 이해하는 데 실패 등으로


는, 당신은 당신의 << 연산자를 선언

Library operator << (ostream &out, const Library & l) 
         ^^^^^^^^^^^ 

그들은 다르다!
간단히 말해서 private 멤버를 클래스의 친구로 액세스 할 때 함수를 선언하지 않으므로 오류가 발생합니다. 또한 이전에 언급 한 것처럼 반환 형식이 올바르지 않습니다.

+0

나는 그것이해야한다는 것을 알고있다. 그래서 나는 아직도 내 이름이 ... 컴파일시에 개인적이라고 말하기 때문에 혼란 스럽다. 도움이된다면 여기에 오류 코드가 있습니다. C : \ Users \ Devin \ Documents \ C++ SMCCLASS \ LibrarySystem \ library.h || 함수에서 'cs52 :: 라이브러리 연산자 << (std :: ostream &, const cs52 :: Library &)': | C : \ Users \ Devin \ Documents \ C++ SMCCLASS \ LibrarySystem \ library.h | 23 | 오류 : 'int cs52 :: Library :: myNumberOfBooksSeenSoFar'는 비공개 | –

+0

@ 대븐 : 확실한가요? 함수 프로토 타입이 처음부터 올바르지 않습니다. –

+0

@ 대변인 : 업데이트 된 답변을 확인하십시오. 귀하의 문제라고 생각합니다. 매개 변수 유형에주의하십시오! –