一个类里面的"this"指针

Jon*_*han 6 c++ pointers this

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

我没有发现任何问题,但我正在使用这个 - >很多,并想知道在进一步之前是否有任何差异.

我在这里看到了对帖子的评论,我不记得哪个帖子,但该人说了一些关于使用关键字"this"的内容.

就个人而言,我觉得直接使用它比变量好.它使代码更容易和漂亮.

sel*_*tze 16

在大多数情况下,没有区别.但有些情况会有所不同:

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

此外,使用模板,您可能需要限定成员,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
    }
};
Run Code Online (Sandbox Code Playgroud)

正确执行"两阶段查找"的编译器会抱怨如果您删除"this->",它不知道我应该是什么."this->"告诉它它是基类的成员.由于基类依赖于模板参数,因此查找会延迟,直到实例化类模板.


Ed *_* S. 12

不,没有真正的区别,它只是一个范围限定符.但是,假设一种方法

void SetFoo( Foo foo )
{
    this->foo = foo;
}
Run Code Online (Sandbox Code Playgroud)

this-> foo是私人会员.在这里,它允许您获取与类/实例变量同名的参数.