What is friend ostream

前端 未结 4 552
北海茫月
北海茫月 2021-01-03 02:24

I\'m a bit confused about what exactly this line of code means in my header file.

friend ostream & operator << (ostream &, const something &         


        
4条回答
  •  野趣味
    野趣味 (楼主)
    2021-01-03 03:13

    A C++ class may declare another class or a function to be a friend. Friendly classes and methods may access private members of the class. So, the free operator method <<, not defined in any class, may insert somethings into a stream and look at and use the private members of something to do its work. Suppose something were complex:

    class complex {
        private:
           double re;
           double im;
        public:
           complex(double real = 0.0, double imag = 0.0) : re(real), im(imag) {}
           friend ostream & operator<<(ostream& os, complex& c);
    };
    
    ostream & operator<<(ostream& os, complex& c){
        os << c.re << std::showpos << c.im;
        return os;
    }
    

提交回复
热议问题