1

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;
    }
4

1 回答 1

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
于 2019-01-11T00:39:18.207 回答