朋友运营商<<重载问题,

Dev*_*ley 1 c++ private class operator-overloading friend

我遇到了我的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);
}
Run Code Online (Sandbox Code Playgroud)

而函数原型和私有变量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
Run Code Online (Sandbox Code Playgroud)

Alo*_*ave 5

您的<<运营商应该具有以下原型:

std::ostream& operator << ( std::ostream &out, const Library & l )
^^^^^^^^^^^^^
Run Code Online (Sandbox Code Playgroud)

您需要返回std::ostream对象的引用,以便链接流操作.

此外,如果您在Library类中声明它是朋友,您应该能够访问Library重载函数中类的所有成员(私有/受保护).


因此我无法理解您的代码,您将<<运营商声明为:

friend Library operator << ( Library& out, const Library & l );
                             ^^^^^^^^^^^^
Run Code Online (Sandbox Code Playgroud)

您使用原型定义了操作员函数:

Library operator << ( ostream &out, const Library & l )
                      ^^^^^^^^^^^
Run Code Online (Sandbox Code Playgroud)

它们是不同的!
简而言之,您从未声明过您作为班级朋友访问私有成员的函数,因此错误.此外,返回类型是不正确的,如前所述.