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

In a C++ class, what's the difference between accessing a member variable with "this"

本文关键字:成员 变量 区别 什么 访问 this C++ 类中 使用      更新时间:2023-10-16

我制作了一个简单的类来表示一扇门。为了返回变量,我使用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++时,你根本不应该说this,除非在非常特殊的情况下。(我唯一能想到的是将指针绑定到成员函数,将实例指针传递到其他对象,以及一些涉及模板和继承的情况(感谢Mooing Duck的最后一个例子(。(

只需为函数参数、局部变量和成员变量提供合理的名称,这样就不会有任何歧义。

最近出现了许多准面向对象的语言,这些语言使"this"answers"new"这两个词在年轻一代中几乎都是"我在使用对象"的同义词,但这不是C++的习惯用法。

在您的情况下没有区别。只有更多的打字工作。

这整件事似乎是多余打字的练习。据我所见,Close可以浓缩为:

void Door::Close() {
    shut = true; 
}

即使在不必要的情况下也要进行赋值,这比仅在当前为false时进行测试和设置要简单得多。

同样值得一提的是(IMO(,这条评论:

Door(); // Constructs a shut door.

似乎不适合实现:

Door::Door()
{}

如果您希望默认的ctor将shut初始化为true,那么您需要/想要添加一些代码来执行此操作。

更糟糕的是,你的IsOpen似乎完全倒退了:

bool Door::isOpen()
{
    return this->shut;
}

如果关闭,则不会打开,反之亦然。

没有区别,除了更多的类型和this->引入的噪声。

void Door::Close()
{
    if(isOpen()) shut = true;
}

这样更可读吗:

void Door::Close()
{
    if(this->isOpen()) this->shut = true;
}

但这只是个人喜好,也是风格的问题。