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

前端 未结 14 753
忘掉有多难
忘掉有多难 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-29 00:08

    I'd argue that providing accessors are more important in C++ than in C#.

    C++ has no builtin support for properties. In C# you can change a public field to a property mostly without changing the user code. In C++ this is harder.

    For less typing you can implement trivial setters/getters as inline methods:

    class Foo
    {
    public:
        const std::string& bar() const { return _bar; } 
        void bar(const std::string& bar) { _bar = bar; } 
    private:
        std::string _bar;
    };
    

    And don't forget that getters and setters are somewhat evil.

提交回复
热议问题