首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >Friend Operator <<重载问题,

Friend Operator <<重载问题,
EN

Stack Overflow用户
提问于 2011-09-20 01:19:46
回答 1查看 286关注 0票数 1

我的operator<<重载有一个问题,无论我做什么,我都不能访问它所在类的私有变量,因为它会说变量是私有的,因为这是一个编译器错误。这是我当前的代码:

代码语言:javascript
复制
#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中的函数原型和私有变量是

代码语言:javascript
复制
#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
EN

回答 1

Stack Overflow用户

发布于 2011-09-20 01:23:46

您的<<操作符应该具有以下原型:

代码语言:javascript
复制
std::ostream& operator << ( std::ostream &out, const Library & l )
^^^^^^^^^^^^^

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

此外,如果在Library类中将其声明为friend,则应该能够在重载函数中访问Library类的所有成员(私有/受保护)。

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

代码语言:javascript
复制
friend Library operator << ( Library& out, const Library & l );
                             ^^^^^^^^^^^^

您使用prototype定义了运算符函数:

代码语言:javascript
复制
Library operator << ( ostream &out, const Library & l )
                      ^^^^^^^^^^^

他们是不同的!

简而言之,您从未声明过函数,在此函数中您将作为类的朋友访问私有成员,从而导致错误。另外,正如我之前提到的,返回类型是不正确的。

票数 5
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/7474763

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档