[英]Friend Operator << overloading issues,
我的operator<<
重載時出現問題,無論如何我都無法訪問該類的私有變量,因為它將表示變量是私有的,這是編譯器錯誤。 這是我當前的代碼:
#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);
}
並且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
您的<<
運算符應具有以下原型:
std::ostream& operator << ( std::ostream &out, const Library & l )
^^^^^^^^^^^^^
您需要返回對std::ostream
對象的引用,以便可以鏈接流操作。
另外,如果您在Library
類中將其聲明為好友,則應該可以訪問重載函數中Library
類的所有成員(私有/受保護)。
因此,我無法理解您的代碼,您將<<
操作符聲明為:
friend Library operator << ( Library& out, const Library & l );
^^^^^^^^^^^^
您使用原型定義了運算符功能:
Library operator << ( ostream &out, const Library & l )
^^^^^^^^^^^
他們是不同的!
簡而言之,您從未將函數作為類的朋友聲明為訪問私有成員的函數,因此不會出錯。 另外,返回類型是不正確的,正如我之前提到的。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.