c++ - 在对象中使用或不使用 'this'

标签 c++ methods this member

<分区>

我的问题是指当我想调用同一个类的其他方法时的情况。使用和不使用“this”有什么区别?与类的变量相同。通过“this”访问这些变量有区别吗?是否与那些方法/变量是私有(private)的还是公共(public)的有关?示例:

class A {
private:
    int i;
    void print_i () { cout << i << endl; }

public:
    void do_something () {

        this->print_i();    //call with 'this', or ...
        print_i();          //... call without 'this'

        this->i = 5;        //same with setting the member;
        i = 5;
    }
};

最佳答案

一般来说,这是一个风格问题。我去过的所有地方 工作时首选不使用 this->,除非 必要的。

在某些情况下它会有所作为:

int func();

template <typename Base>
class Derived : public Base
{
    int f1() const
    {
        return func();      //  calls the global func, above.
    }
    int f2() const
    {
        return this->func();  //  calls a member function of Base
    }
};

在这种情况下,this-> 使函数名称依赖, 这反过来将绑定(bind)推迟到模板是 实例化。如果没有 this->,函数名将是 在定义模板时绑定(bind),而不考虑什么 可能在 Base 中(因为当模板是 定义)。

关于c++ - 在对象中使用或不使用 'this',我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24454124/

相关文章:

c++ - 为什么 tellp() 为 ios::app 返回 0 而不是为 ios::ate?

javascript - 如何让 ESLint 忽略其他文件中的类名和方法?

java - 在 Java 接口(interface)中声明参数子类型,在 Java 实现方法中使用子类型

Python:启动类方法时线程不起作用

使用 C 库头文件的 C++ 程序将 "this"识别为关键字。外部 "C"错误?

c++ - 在构造函数中传递指向对象的指针

c++ - 为什么我的函数会出现乱七八糟的 cout 语句?

coffeescript - "fat arrow"(=>) 何时绑定(bind)到 "this"实例

javascript - JavaScript 代码中与 "this"混淆

c++ - SQLite 预更新 Hook 重入