我的类方法中是否需要“ this指针”?

时间:2019-01-11 00:35:05

标签: c++ this this-pointer

getA()&getB()和setA()&setB()之间有什么区别吗?

如果它们相同,则首选语法是什么?

distance

1 个答案:

答案 0 :(得分:8)

在您的用例中也是如此。通常最好在可能的情况下省略this->,除非您有本地编码样式指南/约定。

当您具有遮盖成员变量的局部变量或参数时,这很重要。例如:

class Enemy {
public:
    int health;
    void setHealth(int health) {
        // `health` is the parameter.
        // `this->health` is the member variable.
        this->health = health;
    }
};

(可选)可以通过在项目中使用命名约定来避免这种情况。例如:

  • 成员变量始终以_后缀,例如health_
  • 成员变量始终以m_为前缀,例如m_health