yourvariable 或 yourvariable 有什么不同吗? 我没有发现任何问题,但我经常使用 this-> 并且想知道在继续之前是否有任何-6ren">
gpt4 book ai didi

c++ - 类中的 "this"指针

转载 作者:可可西里 更新时间:2023-11-01 18:42:04 25 4
gpt4 key购买 nike

问题很简单...出于某种原因直接使用 this->yourvariable 或 yourvariable 有什么不同吗?

我没有发现任何问题,但我经常使用 this-> 并且想知道在继续之前是否有任何区别。

我在这里看到一篇帖子的评论,我不记得是哪个帖子了,但那个人说了一些关于使用关键字“this”的事情。

我个人觉得比直接使用变量好用。它使代码更简单、更漂亮。

最佳答案

在大多数情况下没有区别。但在某些情况下它会有所作为:

class foo
{
int i;
void bar() {
int i = 3;
i; // refers to local i
this->i; // refers to the member i
}
};

此外,对于模板,您可能需要使用 this-> 来限定成员,以便延迟名称查找:

template<typename T>
struct A
{
int i;
T* p;
};

template<typename T>
struct B : A<T>
{
void foo() {
int k = this->i; // here this-> is required
}
};

正确执行“两阶段查找”的编译器会在您删除“this->”时提示它不知道 i 应该是什么。 “this->”告诉它它是基类的成员。由于基类依赖于模板参数,查找会延迟到类模板被实例化。

关于c++ - 类中的 "this"指针,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1610158/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com