2016-06-30 12 views
3

私はこのような他の質問を見ましたが、私は解決策を得られませんでした。フレンドostreamプライベートメンバーにアクセスすることはできません

cout_overload.h:

#ifndef COUT_OVERLOAD_H_ 
#define COUT_OVERLOAD_H_ 

      #include <iostream> 

      class A 
      { 
        private: 
          int data; 
        public: 
          A(int d); 
          friend std::ostream & operator << 
          (std::ostream os, const A &t); 
      }; 

#endif 

cout_overload_r.cpp:

#include <iostream>                  
    #include "cout_overload.h" 

    A::A(int d) 
    { 
      data = d; 
    } 

    std::ostream &operator << (std::ostream &os, const A&t) 
    { 
      os << " t = " << t.data ; 
      return os; 
    }  

main.cppに:

#include <iostream>                  #include "cout_overload.h" 

int main(void) 
    { 
      A ra(1); 
      using std::cout; 

    //  cout<<ra; 

     return 0; 
} 

エラーコンパイル中: enter image description hereここでは、コードされ

+3

'std :: ostream'と' std :: ostream 'は同じではありません。 – songyuanyao

+0

良いところ@songyuanyao – Neil

答えて

3

あなたは出力ストリームである

friend std::ostream & operator << (std::ostream &os, const A &t); 

ostreamので、あなたのfriend機能を変更し、

friend std::ostream & operator << (std::ostream os, const A &t); 

ostream&を使用し、上記の行を交換する必要があり、&は、(参照によって渡すことですストリームを関数に渡す唯一の方法)。

関連する問題