在 C++ 类中,使用 "this" 访问成员变量有什么区别
In a C++ class, what's the difference between accessing a member variable with "this"
我制作了一个简单的类来表示一扇门。为了返回变量,我使用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;
}
但这只是个人喜好,也是风格的问题。
相关文章:
- 将成员变量添加到共享库中的类中,不会破坏二进制兼容性吗
- 具有奇怪重复模板模式的派生类中的成员变量已损坏
- 内置函数可查看CPP中的成员变量
- 是否可以初始化不可复制类型的成员变量(或基类)
- 将包含C样式数组的对象初始化为成员变量(C++)
- 为什么我不能在一个类的不同行中声明和定义成员变量?
- 在循环中按顺序遍历成员变量
- c++类声明时,相同的例程,不同的成员变量类型
- 如何从另一个文件继承私有成员变量和公共函数
- 在C++类中,是否必须初始化作为数组的成员变量
- 如何从子成员函数修改父公共成员变量
- 我可以在 C++ 中将数据成员/变量从其定义之外添加到结构中吗?
- 从私有成员变量的成员方法返回unique_ptr
- 在派生类中使用基类的私有成员变量的最佳方法
- 静态 constexpr 类成员变量对多线程读取是否安全?
- C++:是否可以使用非静态成员变量模板?
- 打印所有继承的类成员变量和方法
- 如何在复杂继承中访问静态成员变量
- 为什么我不能在返回 const 的布尔函数中为类成员变量赋值?C++
- 成员变量与函数概念检查