Why use prefixes on member variables in C++ classes

前端 未结 29 1356
半阙折子戏
半阙折子戏 2020-11-28 17:39

A lot of C++ code uses syntactical conventions for marking up member variables. Common examples include

  • m_memberName for public members (where public
29条回答
  •  一向
    一向 (楼主)
    2020-11-28 17:45

    I use it because VC++'s Intellisense can't tell when to show private members when accessing out of the class. The only indication is a little "lock" symbol on the field icon in the Intellisense list. It just makes it easier to identify private members(fields) easier. Also a habit from C# to be honest.

    class Person {
       std::string m_Name;
    public:
       std::string Name() { return m_Name; }
       void SetName(std::string name) { m_Name = name; }
    };
    
    int main() {
      Person *p = new Person();
      p->Name(); // valid
      p->m_Name; // invalid, compiler throws error. but intellisense doesn't know this..
      return 1;
    }
    

提交回复
热议问题