Are get and set functions popular with C++ programmers?

前端 未结 14 745
忘掉有多难
忘掉有多难 2020-11-28 23:12

I\'m from the world of C# originally, and I\'m learning C++. I\'ve been wondering about get and set functions in C++. In C# usage of these are quite popular, and tools like

14条回答
  •  北海茫月
    2020-11-28 23:54

    In your example:

    class Foo
    {
    public:
        const std::string GetBar(); // Should this be const, not sure?
    

    You probably mean this:

    std::string GetBar() const;
    

    Putting the const at the end means "This function doesn't modify the Foo instance it is called on", so in a way it marks it as a pure getter.

    Pure getters occur frequently in C++. An example in std::ostringstream is the str() function. The Standard library often follows a pattern of using the same function name for a pair of getter/setter functions - str being an example again.

    As to whether it's too much work to type out, and is it worth it - that seems an odd question! If you need to give clients access to some information, provide a getter. If you don't, then don't.

提交回复
热议问题