语法this-> func()和func()之间是否存在细微差别?

jan*_*vak 2 c++ virtual-functions

如果我有一个具有虚函数且没有自由函数的类,那么this->func()和之间是否存在差异func()

class Base {
    virtual void A() { std::cout << "Base" << std::endl; };
    void B() { this->A(); };
    void C() { A(); };
};

class Derived : public Base {
    virtual void A() { std::cout << "Derived" << std::endl; };
    void B2() { this->A(); };
    void C2() { A(); };
};
Run Code Online (Sandbox Code Playgroud)

是否有方法的执行任何差异B()C()?怎么样的方法B2()C2()

tem*_*def 7

在您发布的示例中,两种语法之间没有区别.它们完全相同.

有两种情况存在差异.一种是如果你有一个模板类,它继承自依赖于模板参数的类型.例如:

template <typename T> class Base {
public:
    void doSomething() const {
       std::cout << "Do ALL the things!" << std::endl;
    }
};

template <typename T> class Derived: public Base<T> {
public:
    void doSomethingElse() const {
        doSomething();       // Error!
        this->doSomething(); // Okay
    }
};
Run Code Online (Sandbox Code Playgroud)

这里,由于Derived<T>继承自Base<T>依赖于模板参数的类型,因此名称查找是在两步过程中完成的.如果doSomething使用非限定语法调用,则编译器不知道Base<T>要查找它并报告错误.但是,如果你说this->doSomething(),它知道你正在调用一个成员函数,并最终会发现它应该查看它Base<T>.

如果在函数内声明了一个本地对象,其名称与成员函数相同,则会出现另一种情况.例如:

class ThisIsSillyDontDoThisLikeSeriouslyDont {
public:
    void doSomething() const {
        std::cout << "Do ALL the things!" << std::endl;
    }

    void weirdFunction() const {
        auto doSomething = [] {
            std::cout << "I'm afraid there's nothing to be done" << std::endl;
        };

        doSomething();       // Calls the local function
        this->doSomething(); // Calls the member function
    }
};
Run Code Online (Sandbox Code Playgroud)

第二种情况非常罕见,以至于我从未见过它,而且我甚至可以说它的编码风格很差.

除了这些罕见的情况之外,使用和不this->使用前缀调用成员函数之间没有区别.