在您發佈的例子中,有兩種語法之間沒有什麼區別。它們完全相同。
有兩種情況是有區別的。一個是如果你有一個模板類繼承自一個依賴於模板參數的類型。例如:從類型Base<T>
,它依賴於模板參數
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
}
};
在此,由於Derived<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
}
};
這第二種情況是如此罕見,我從來沒有見過它,我會走這麼遠至可以說,它的編碼風格,真是可憐。
從這些罕見的情況下
除此之外,雖然,有呼籲自己的成員函數與不this->
作爲前綴之間沒有區別。
完全的文體。 – user4581301