我的班级方法中是否需要"this pointer"?

arm*_*m.u 1 c++ this this-pointer

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

如果它们是相同的,这是首选语法?

    class A{
    public:
        int x;

        int getA(){return x;}
        int getB(){return this->x;}
        void setA(int val){ x = val;}
        void setB(int val){ this->x = val;}

    };

    int main(int argc, const char * argv[]) {
        A objectA;
        A objectB;

        object.setA(33);
        std::cout<< object.getA() << "\n";

        objectB.setB(32);
        std::cout<< object.getB() << "\n";

        return 0;
    }
Run Code Online (Sandbox Code Playgroud)

mia*_*t17 8

在您的用例中也是如此.this->除非您有本地编码风格指南/惯例,否则通常首选省略.

当你有一个影响成员变量的局部变量或参数时,这很重要.例如:

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

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

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