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)
方法只是自动化.