C++ 成员变量

标签 c++ class variables scope member

考虑以下类:

class A
{
  A();
  int number;
  void setNumber(int number);
};

您可以通过 3 种方式实现“setNumber”:

方法一:使用'this'指针。

void A::setNumber(int number)
{
  this->number = number;
}

方法二:使用范围解析运算符。

void A::setNumber(int number)
{
  A::number = number;
}

方法 3:改为使用“m”或“_”表示所有成员变量(这是我的首选方法)。

void A::setNumber(int number)
{
  mNumber = number;
}

这只是个人喜好,还是选择特定方法有好处?

最佳答案

这主要是个人喜好,但让我从一家同时制作许多小游戏的公司内部分享我对这个问题的看法(因此我周围使用了许多编码风格)。

此链接有几个很好的相关答案:Why use prefixes on member variables in C++ classes

您的选择 1:

void A::setNumber(int number)
{
  this->number = number;
}

First off, many programmers tend to find this cumbersome, to continually type out the ' this-> '. Second, and more importantly, if any of your variables shares a name with a parameter or a local variable, a find-replace designed to say, change the name of 'number' might affect the member variables located in the find-replace scope as well.

您的选择 2:

void A::setNumber(int number)
{
  A::number = number;
}

The problem I've run into with this, is that in large classes, or classes with large functions (where you cannot see the function or the class is named unexpectedly), the formatting of A::(thing) looks very much like accessing a part of a namespace, and so can be misleading. The other issue is the same as #2 from the previous option, if your names are similar to any variables you're using there can be unexpected confusion sometimes.

您的选择 3:

void A::setNumber(int number) 
{
  mNumber = number;
}

This is the best of those three presented options. By creating (and holding to!) a syntax that involves a clear and meaningful prefix, you not only create a unique name that a local (or global) variable won't share, but you make it immediately clear where that variable is declared, regardless of the context you find it in. I've seen it done both like this ' mVariable ' and like this 'm_variable' and it mostly depends upon if you prefer underscores to uppercase concatenation. In addition, if your style tends to add things like ' p 's on for pointers, or ' g 's on for globals, this style will mesh well and be expected by readers.

关于C++ 成员变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10198046/

相关文章:

javascript - document.location.href 重置全局变量

c++ - 捕获列表中捕获的行为 [c++]

c++ - 在构建时将对象存储在 vector 中

c# 如何从类中返回值?

ruby - 将匿名类分配给常量时是否有钩子(Hook)?

mysql 使用包含变量的 mysql 查询创建 View

c++ - Box2d c++ 与 ActionScript b2Body SetPosition 有什么相似之处?

c++ - 初始化结构 vector

class - UML:《原始语》的含义

javascript - 将 javascript 事件监听器附加到变量的理论?