开发者

Friend Operator << overloading issues,

开发者 https://www.devze.com 2023-04-06 11:02 出处:网络
I\'m having an issue with my operator<< overloading where I can not access the private variables of the class it is in no matter what I do because it will say that the variables are private as a

I'm having an issue with my operator<< overloading where I can not access the private variables of the class it is in no matter what I do because it will say that the variables are private as a compiler error. This is my current code:

#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);
}

And the function prototype and private variables in library.h are

#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


Your << operator should have this protoype:

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

You need to return a reference to std::ostream object so that you can chain stream operations.

Also, If you declare it as friend in your Library class you should be able to access all the members(private/protected) of the Library class in your overloaded function.


As such i fail to understand your code, You declared your << operator as:

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

You defined your operator function with prototype:

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

They are different!
In short you never declared the function where you are accessing the private member as a friend of your class and Hence the error. Also, the return type is Incorrect as I mentioned before.

0

精彩评论

暂无评论...
验证码 换一张
取 消