Why use prefixes on member variables in C++ classes

前端 未结 29 1341
半阙折子戏
半阙折子戏 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:43

    Other languages will use coding conventions, they just tend to be different. C# for example has probably two different styles that people tend to use, either one of the C++ methods (_variable, mVariable or other prefix such as Hungarian notation), or what I refer to as the StyleCop method.

    private int privateMember;
    public int PublicMember;
    
    public int Function(int parameter)
    {
      // StyleCop enforces using this. for class members.
      this.privateMember = parameter;
    }
    

    In the end, it becomes what people know, and what looks best. I personally think code is more readable without Hungarian notation, but it can become easier to find a variable with intellisense for example if the Hungarian notation is attached.

    In my example above, you don't need an m prefix for member variables because prefixing your usage with this. indicates the same thing in a compiler-enforced method.

    This doesn't necessarily mean the other methods are bad, people stick to what works.

提交回复
热议问题