• If we want that operator + can support (int + MyTime) ```cpp MyTime t1(2, 40); 20 + t1;
    1. - Let a friend function to help
    2. - Friend functions
    3. - Declare in a class body -> 在类内部声明
    4. - Granted class access to members (including private members) -> 有获取所有类内成员的能力
    5. - But not members -> 其不是类的成员
    6. :::info
    7. friend functions are not members! They just declared in the class body.
    8. :::
    9. ```cpp
    10. class MyTime
    11. {
    12. // ...
    13. public:
    14. friend MyTime operator+(int m, const MyTime & t)
    15. {
    16. return t + m;
    17. }
    18. };
    • 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; }

    1. - Operator `<<` can also be overloaded.
    2. - But in (cout << t1; ) , the first operand is std::ostream, not MyTime.
    3. - To modify the definition of **std::ostream? No!**
    4. - Use a friend function
    5. ```cpp
    6. friend std::ostream & operator<<(std::ostream & os, const MyTime & t)
    7. {
    8. std::string str = std::to_string(t.hours) + " hours and "
    9. + std::to_string(t.minutes) + " minutes.";
    10. os << str;
    11. return os;
    12. }
    13. friend std::istream & operator>>(std::istream & is, MyTime & t);