c++ - friend keyword for operator overloading -
i tried write simple example <<-operator-overloading. before, i've never used keyword "friend". not work without it. mistake did or why need friend keyword here?
class rational{ public: rational(double num, double count) : n(num),c(count){} rational& operator+=(const rational& b){ this->n+= b.n; this->c+= b.c; return *this; } friend std::ostream& operator<<(std::ostream& os, const rational& obj) { std::cout << obj.n << "," << obj.c << std::endl; return os; } private: double n; double c; };
thanks
you want stream objects internals not accessible through class' public interface, operator can't @ them. have 2 choices: either put public member class streaming
class t { public: void stream_to(std::ostream& os) const {os << obj.data_;} private: int data_; };
and call operator:
inline std::ostream& operator<<(std::ostream& os, const t& obj) { obj.stream_to(os); return os; }
or make operator friend
class t { public: friend std::ostream& operator<<(std::ostream&, const t&); private: int data_; };
so can access class' private parts:
inline std::ostream& operator<<(std::ostream& os, const t& obj) { os << obj.data_; return os; }
Comments
Post a Comment