Operator << overloading

前端 未结 1 1934
不思量自难忘°
不思量自难忘° 2020-12-20 09:22

I\'m working on my project and I want to overload operator << which should print out my object on console.
Object is called \"config\" and in its temp

1条回答
  •  半阙折子戏
    2020-12-20 10:01

    Here's one way to solve the problem.

    1. Declare the operator<< function first, before config is defined. In order to declare the function, you have to forward declare the class template.

      template  class config;
      template  std::ostream& operator<<(std::ostream &out,
                                                     const config &c);
      
    2. In the class, make the function a friend by using T as the template parameter.

      friend ostream& operator<< (ostream &out, const config &c);
      // Notice  this            ^^^^
      // This makes sure that operator<<  is not a friend of
      // config. Only operator<<  is a friend of
      // config
      

    Here's a working program with those changes:

    #include 
    #include 
    
    template  class config;
    template  std::ostream& operator<<(std::ostream &out,
                                                   const config &c);
    
    template  class config
    {
        T *attribute1, *attribute2, *attribute3, *attribute4;
        std::string attribName1, attribName2, attribName3, attribName4;
      public:
        config(void)
        {
          attribute1 = new T[3];
          attribute2 = new T[3];
          attribute3 = new T[3];
          attribute4 = new T[3];
        }   
    
        ~config(void)//destructor
         {
           delete [] attribute1;
           delete [] attribute2;
           delete [] attribute3;
           delete [] attribute4;
         }
    
        //operator
        friend std::ostream& operator<< (std::ostream &out,
                                            const config &c);
    };
    
    template  std::ostream& operator<<(std::ostream &out,
                                                   const config &c)
    {
       for(int i=0;i<3;i++)
       {
          out << c.attribute1[i] << " "
              << c.attribute2[i] << " "
              << c.attribute3[i] << " "
              << c.attribute2[i] << std::endl;
       }
       return out;
    }
    
    int main()
    {
       config x;
       std::cout << x << std::endl;
    }
    

    Output:

    0 0 0 0
    0 0 0 0
    0 0 0 0
    
    

    0 讨论(0)
提交回复
热议问题