2016-01-20 19 views
0

我在Base類中有一個方法,該方法返回對this的取消引用。我想在Derived類中使用這種方法,但也可以稍微擴展一下。這個例子會爲自己說話:將取消引用返回到「this」的替代方法

#include <iostream> 

class Base { 
    private: 
    int value = 0; 

    public: 
    int getValue() { return value; } 
    virtual Base& increase() { 
     value++; 
     return *this; 
    } 
}; 

class Derived : public Base { 
    public: 
    Derived& increase() { 
     Base::increase(); 
     if (getValue() == 1) std::cout << "Success" << std::endl; 

     return *this; 
    } 
}; 

據我瞭解,在上述實施Base::increase();只會在一個臨時分配Base對象增加一些value。我該如何解決它?

+2

沒有,這裏沒有臨時對象。 'Base :: increase()'意味着從'Base'類中調用'increase()'實現。 –

回答

4

Base::increase();調用this(不涉及臨時對象)的基本方法。

你甚至可以把它寫像,如果是更清楚你

this->Base::increase(); 
+0

他的例子會編譯。即使C++ 98在重寫函數中也支持反向變量返回類型。見http://cpp.sh/3l52n(評論是錯誤的迴應「不會編譯」評論 - 已被刪除) –