我的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发布于 2011-09-20 01:23:46
您的<<操作符应该具有以下原型:
std::ostream& operator << ( std::ostream &out, const Library & l )
^^^^^^^^^^^^^您需要返回一个对std::ostream对象的引用,以便您可以链接流操作。
此外,如果在Library类中将其声明为friend,则应该能够在重载函数中访问Library类的所有成员(私有/受保护)。
因此,我无法理解您的代码,您将<<运算符声明为:
friend Library operator << ( Library& out, const Library & l );
^^^^^^^^^^^^您使用prototype定义了运算符函数:
Library operator << ( ostream &out, const Library & l )
^^^^^^^^^^^他们是不同的!
简而言之,您从未声明过函数,在此函数中您将作为类的朋友访问私有成员,从而导致错误。另外,正如我之前提到的,返回类型是不正确的。
https://stackoverflow.com/questions/7474763
复制相似问题