gpt4 book ai didi

c++ - 有什么理由使用这个->

转载 作者:IT老高 更新时间:2023-10-28 22:15:33 25 4
gpt4 key购买 nike

我使用 C++ 编程多年,但我仍然对一件事存有疑问。在其他人代码的许多地方,我看到类似:

void Classx::memberfunction()
{
this->doSomething();
}

如果我需要导入/使用该代码,我只需删除 this-> 部分,我从未见过任何损坏或有副作用。

void Classx::memberfunction()
{
doSomething();
}

那么,你知道使用这种结构的任何理由吗?

编辑:请注意,我在这里谈论的是成员函数,而不是变量。我知道当您想区分成员变量和函数参数时可以使用它。

编辑:明显重复: Are there any reasons not to use "this" ("Self", "Me", ...)?

最佳答案

真正发挥作用的唯一地方是派生类中的模板:

template<typename T>
class A {
protected:
T x;
};

template<typename T>
class B : A<T> {
public:
T get() {
return this->x;
}
};

由于 details in the name lookup in C++ compilers ,必须明确说明 x 是类的(继承的)成员,使用 this->x 最容易做到。但这是一个相当深奥的案例,如果您没有模板化的类层次结构,您实际上不需要显式使用 this 来访问类的成员。

关于c++ - 有什么理由使用这个->,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/577243/

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