4

I have seen other questions like this but I didn't get a solution. Here is the code:

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

the error during compiling: enter image description here

Abhineet
  • 5,320
  • 1
  • 25
  • 43
tanyu Fei
  • 63
  • 3

1 Answers1

3

You need to modify your friend function and Use ostream& inside the

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

And replace your above line,

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

Because ostream is an output stream, the & is to pass by reference ( the only way to pass streams to functions )..

msc
  • 33,420
  • 29
  • 119
  • 214