【问题标题】:Friend Operator << overloading issues,Friend Operator << 重载问题,
【发布时间】:2011-09-19 17:19:46
【问题描述】:

我的operator&lt;&lt; 重载存在问题,无论我做什么,我都无法访问它所在的类的私有变量,因为它会说这些变量是私有的,因为编译器错误。这是我当前的代码:

#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

【问题讨论】:

    标签: c++ class operator-overloading private friend


    【解决方案1】:

    你的&lt;&lt; 操作员应该有这个原型:

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

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

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


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

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

    你用原型定义了你的操作符函数:

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

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

    【讨论】:

    • 我知道我应该这样做,这就是为什么我很困惑,因为它仍然说 myNum... 在编译时是私有的。如果有帮助,这是错误代码。 C:\Users\Devin\Documents\C++ SMCCLASS\LibrarySystem\library.h||在函数'cs52::Library operator
    • @Devin:你确定吗?您的函数原型一开始就不正确。
    • @Devin:检查更新的答案,我认为这是你的问题。注意参数类型!
    • 这是正确答案。问题中的代码甚至无法编译,因为类型都是错误的。
    猜你喜欢
    • 2013-11-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-03-25
    • 2012-10-25
    • 1970-01-01
    相关资源
    最近更新 更多