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

前端 未结 14 763
忘掉有多难
忘掉有多难 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:50

    If you use C++/CLI as your varient of C++, then it has native property support in the language, so you can use

    property String^ Name;
    

    This is the same as

    String Name{get;set;}
    

    in C#. If you need more precise control over the get/set methods then you can use

    property String^ Name
    {
       String^ get();
       void set(String^ newName);
    }
    

    in the header and

    String^ ClassName::Name::get()
    {
       return m_name;
    }
    
    void ClassName::Name::set(String^ newName)
    {
       m_name = newName;
    }
    

    in the .cpp file. I can't remember off hand, but I think you can have different access permissions for the get and set methods (public/private etc).

    Colin

提交回复
热议问题