How Non-Member Functions Improve Encapsulation

后端 未结 8 990
心在旅途
心在旅途 2020-11-29 08:47

I read Scott Meyers\' article on the subject and quite confused about what he is talking about. I have 3 questions here.

Question 1

To expl

8条回答
  •  星月不相逢
    2020-11-29 09:09

    The meaning f needs type conversions on it left-most arg is as follows:

    consider following senario :

    Class Integer 
    {  
        private: 
           int num;
         public:
            int getNum( return num;)
            Integer(int n = 0) { num = n;}
    
        Integer(const Integer &rhs)) { num = rhs.num ;}
        Integer operator * (const Integer &rhs)
        {
             return Integer(num * rhs.num);
        }
    }
    
    
    int main()
    {
        Integer i1(5);
    
        Integer i3 = i1 *  3; // valid 
    
        Integer i3 = 3 * i1 ; // error     
    }
    

    In above code i3 = i1 * 3 is equivalent to this->operator*(3) which is valid since 3 is implicitly converted to Integer.

    Where as in later i3 = 3 * i1 is equivalent to 3.operator*(i1) , as per rule when u overload operator using member function the invoking object must be of the same class. but here its not that.

    To make Integer i3 = 3 * i1 work one can define non-member function as follow :

    Integer operator * (const Integer &lhs , const Integer &rhs) // non-member function
        {
    
             return Integer(lhs.getNum() * rhs.getNum());
    
        }
    

    I think you will get idea from this example.....

提交回复
热议问题