C++ getters/setters coding style

前端 未结 8 1470
小蘑菇
小蘑菇 2020-11-27 10:41

I have been programming in C# for a while and now I want to brush up on my C++ skills.

Having the class:

class Foo
{
    const std::string& name         


        
8条回答
  •  無奈伤痛
    2020-11-27 11:42

    Using a getter method is a better design choice for a long-lived class as it allows you to replace the getter method with something more complicated in the future. Although this seems less likely to be needed for a const value, the cost is low and the possible benefits are large.

    As an aside, in C++, it's an especially good idea to give both the getter and setter for a member the same name, since in the future you can then actually change the the pair of methods:

    class Foo {
    public:
        std::string const& name() const;          // Getter
        void name(std::string const& newName);    // Setter
        ...
    };
    

    Into a single, public member variable that defines an operator()() for each:

    // This class encapsulates a fancier type of name
    class fancy_name {
    public:
        // Getter
        std::string const& operator()() const {
            return _compute_fancy_name();    // Does some internal work
        }
    
        // Setter
        void operator()(std::string const& newName) {
            _set_fancy_name(newName);        // Does some internal work
        }
        ...
    };
    
    class Foo {
    public:
        fancy_name name;
        ...
    };
    

    The client code will need to be recompiled of course, but no syntax changes are required! Obviously, this transformation works just as well for const values, in which only a getter is needed.

提交回复
热议问题