Operator << overloading

前端 未结 1 1932
不思量自难忘°
不思量自难忘° 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 <typename T> class config;
      template <typename T> std::ostream& operator<<(std::ostream &out,
                                                     const config<T> &c);
      
    2. In the class, make the function a friend by using T as the template parameter.

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

    Here's a working program with those changes:

    #include <string>
    #include <iostream>
    
    template <typename T> class config;
    template <typename T> std::ostream& operator<<(std::ostream &out,
                                                   const config<T> &c);
    
    template <typename T> 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<< <T>(std::ostream &out,
                                            const config &c);
    };
    
    template <typename T> std::ostream& operator<<(std::ostream &out,
                                                   const config<T> &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<double> x;
       std::cout << x << std::endl;
    }
    

    Output:

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