C++ getters/setters coding style

前端 未结 8 1467
小蘑菇
小蘑菇 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:31

    Even though the name is immutable, you may still want to have the option of computing it rather than storing it in a field. (I realize this is unlikely for "name", but let's aim for the general case.) For that reason, even constant fields are best wrapped inside of getters:

    class Foo {
        public:
            const std::string& getName() const {return name_;}
        private:
            const std::string& name_;
    };
    

    Note that if you were to change getName() to return a computed value, it couldn't return const ref. That's ok, because it won't require any changes to the callers (modulo recompilation.)

提交回复
热议问题