getters and setters style

前端 未结 13 2736
猫巷女王i
猫巷女王i 2021-01-01 12:05

(Leaving aside the question of should you have them at all.)

I have always preferred to just use function overloading to give you the same name for both getter and s

13条回答
  •  感动是毒
    2021-01-01 12:16

    Another issue no one else has mentioned is the case of function overloading. Take this (contrived and incomplete) example:

    class Employee {
        virtual int salary() { return salary_; }
        virtual void salary(int newSalary) { salary_ = newSalary; }
    };
    
    class Contractor : public Employee {
        virtual void salary(int newSalary) {
            validateSalaryCap(newSalary);
            Employee::salary(newSalary);
        }
        using Employee::salary; // Most developers will forget this
    };
    

    Without that using clause, users of Contractor cannot query the salary because of the overload. I recently added -Woverloaded-virtual to the warning set of a project I work on, and lo and behold, this showed up all over the place.

提交回复
热议问题