C++ getters/setters coding style

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

    It tends to be a bad idea to make non-const fields public because it then becomes hard to force error checking constraints and/or add side-effects to value changes in the future.

    In your case, you have a const field, so the above issues are not a problem. The main downside of making it a public field is that you're locking down the underlying implementation. For example, if in the future you wanted to change the internal representation to a C-string or a Unicode string, or something else, then you'd break all the client code. With a getter, you could convert to the legacy representation for existing clients while providing the newer functionality to new users via a new getter.

    I'd still suggest having a getter method like the one you have placed above. This will maximize your future flexibility.

提交回复
热议问题