【问题标题】:Friend ostream can't access private member好友ostream无法访问私人会员
【发布时间】:2016-11-02 04:59:20
【问题描述】:

我看到过类似的其他问题,但我没有得到解决方案。 代码如下:

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

编译时的错误:

【问题讨论】:

  • std::ostreamstd::ostream&amp; 不一样。
  • 好地方@songyuanyao

标签: c++ operator-overloading iostream


【解决方案1】:

你需要修改你的friend函数并在里面使用ostream&amp;

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

并替换上面的行,

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

因为ostream 是一个输出流,所以&amp; 是通过引用传递(将流传递给函数的唯一方法)..

【讨论】:

    猜你喜欢
    • 2021-11-15
    • 2015-08-03
    • 2021-01-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多