How Non-Member Functions Improve Encapsulation

后端 未结 8 973
心在旅途
心在旅途 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

    Question : 2

    Scott Meyers has also suggested following thing if u remember :

    --> Keep the class interface complete and minimal.

    See following scenario :

    class Person {
    
    private: string name;
    
             unsigned int age;
    
             long salary;
    
    public:
    
           void setName(string);// assme the implementation
    
           void setAge(unsigned int); // assme the implementation
    
           void setSalary(long sal); // assme the implementation
    
           void setPersonData()
           {
               setName("Scott");
               setAge(25);
               selSalary(50000);
            }
    }
    

    here setPersonData() is member function but ultimately what its doing can also be achieved by making it non - member function like this and it will keep interface of class minimal and does not bloat class with plenty of member function unnecessarily .

       void setPersonData(Person &p) 
       {           
           p.setName("Scott");
           p.setAge(25);
           p.selSalary(50000);
        }
    

提交回复
热议问题