我做了一个简单的类来代表一扇门。为了返回变量,我使用 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;
}
这里可能有也可能没有区别,但是对于更复杂的类呢?
最佳答案
没有。如果您排除 this
指针,则会自动添加它。
只有在执行以下操作时才需要使用它:
void Door::foo(bool shut)
{
this->shut = shut; // this is used to avoid ambiguity
}
简要概述:
将方法视为将指针作为第一个参数传递的函数。
void Door::foo(int x) { this->y = x; } // this keyword not needed
大致等同于
void foo(Door* this_ptr, int x) { this_ptr->y = x; }
方法只是自动执行此操作。
关于c++ - 在 C++ 类中,使用 "this"访问成员变量有什么区别,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8002359/