在C++类中,使用"this"访问成员变量之间的区别是什么

duk*_*vin 5 c++ pointers class

我做了一个简单的课来代表一扇门.要返回变量,我用this指针访问它们.关于只是访问变量,使用this指针访问它们之间的区别是什么?

class Door
{
protected:
    bool shut; // true if shut, false if not shut
public:
    Door(); // Constructs a shut door.
    bool isOpen(); // Is the door open?
    void Open(); // Opens the door, if possible. By default it
    // is always possible to open a generic door.
    void Close(); // Shuts the door.
};
Door::Door()
{}
bool Door::isOpen()
{
    return this->shut;
}
void Door::Open()
{
    this->shut = false;
}
void Door::Close()
{
    if(this->isOpen()) this->shut = true;
}
Run Code Online (Sandbox Code Playgroud)

这里可能存在差异,也可能没有区别,但更复杂的课程呢?

Pub*_*bby 10

没有.该this如果排除它的指针会自动添加.

如果您正在执行以下操作,则只需使用它:

void Door::foo(bool shut)
{
    this->shut = shut; // this is used to avoid ambiguity
}
Run Code Online (Sandbox Code Playgroud)

更多用法


简要概述:

将方法视为将指针作为第一个参数传递的函数.

void Door::foo(int x) { this->y = x; } // this keyword not needed
Run Code Online (Sandbox Code Playgroud)

大致相当于

void foo(Door* this_ptr, int x) { this_ptr->y = x; }
Run Code Online (Sandbox Code Playgroud)

方法只是自动化.

  • 极端迂回警报:使用模板时可能会出现问题,因为可能是这种情况 - >成员是从属名称,成员不是从属名称. (4认同)
  • 还有其他一些用途,例如当你有一个"门*"的功能时,你可以传递它`this`.但+1表示何时使用`this->`. (2认同)