- If we want that operator
+can support (int+ MyTime) ```cpp MyTime t1(2, 40); 20 + t1;
- Let a friend function to help- Friend functions- Declare in a class body -> 在类内部声明- Granted class access to members (including private members) -> 有获取所有类内成员的能力- But not members -> 其不是类的成员:::infofriend functions are not members! They just declared in the class body.:::```cppclass MyTime{// ...public:friend MyTime operator+(int m, const MyTime & t){return t + m;}};
- A friend function is defined out of the class.
- No
MyTime::before its function name ```cpp class MyTime { // … public: friend MyTime operator+(int m, const MyTime & t); };
MyTime operator+(int m, const MyTime & t) { return t + m; }
- Operator `<<` can also be overloaded.- But in (cout << t1; ) , the first operand is std::ostream, not MyTime.- To modify the definition of **std::ostream? No!**- Use a friend function```cppfriend std::ostream & operator<<(std::ostream & os, const MyTime & t){std::string str = std::to_string(t.hours) + " hours and "+ std::to_string(t.minutes) + " minutes.";os << str;return os;}friend std::istream & operator>>(std::istream & is, MyTime & t);
