好友运算符<<过载问题,

Friend Operator << overloading issues,

本文关键字:lt 问题 好友 运算符      更新时间:2023-10-16

我有一个问题,我的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 );
                             ^^^^^^^^^^^^

你用prototype定义了运算符函数:

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

他们是不同的!
简而言之,您从未将访问私有成员的函数声明为类的友元,因此会出现错误。此外,正如我之前提到的,返回类型是不正确的。