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

标签 c++ class pointers

我做了一个简单的类来代表一扇门。为了返回变量,我使用 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
}

More usages


简要概述:

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

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/

相关文章:

c++ - 将 C/C++ 线程附加到套接字

c++ - 内部类的任何解决方案或编程技巧?

交换指针的 C++ 函数在作用域内工作

c++ - 使用指针和函数的 C++ 菜单

c - 无法使用 mmap 从结构中读取指针

c++ - c++双向链表的相反元素的成对乘法

c++ - 如何通过 WinAPI 使用不带连字的字体?

c# - 添加依赖于第一个类型的第二个类型时出错

excel - 从项目集合中调用项目

ios - 不能从另一个类调用对象