2015-11-12 159 views
0

我試圖實現shared_ptr的簡化版本。但在編譯期間,編譯器彈出使用未聲明的標識符的錯誤。但是,我確實聲明瞭變量。爲什麼在派生類中找不到基類成員C++

有人能幫我找出原因嗎? 在此先感謝。

的代碼如下:

template <typename T> 
class S_ptr 
{ 
// private classes definition 
private: 
    template <typename T2> 
    class DefaultDeleter 
    { 
    public: 
     void operator()(T2* p) { delete p; } 
    }; 

    class Aux 
    { 
     template<typename> friend class S_ptr; 
    public: 
     // constructor & destructor 
     Aux() : ref_count_(1) {} 

     virtual ~Aux() {} 

     // member method 
     virtual void incre() { ++ref_count_; } 
     virtual void decre() = 0; 
     virtual void destroy() = 0; 

    protected: 
     unsigned int ref_count_; // UNDECLARED IDENTIFIER 
    }; 

    template <typename T2, typename Deleter> 
    class AuxCounter : public Aux 
    { 
    public: 
     // constructor & destructor 
     AuxCounter(T2* p, Deleter d) : ptr_(p), deleter_(d) {} 

     ~AuxCounter() { decre(); } 

     // member method 
     void decre() override { if(--ref_count_ == 0) destroy(); } // ERROR 
     void destroy() override { deleter_(ptr_); } 

     //public member 
     T2* ptr_; 
    private: 
     Deleter deleter_; 
    }; 
    // private class defination end 

public: 
    // constructor & destructor 
    S_ptr(T* p) : ptr_(new T(*p)) 
    { 
     counter_ = new AuxCounter<T, DefaultDeleter<T>>(ptr_,  DefaultDeleter<T>()); 
     delete p; 
     p = nullptr; 
    } 
    template <typename T2, typename D> S_ptr(T2* p, D&& deleter) :  ptr_(new T(*p)) 
    { 
     counter_ = new AuxCounter<T, D>(new T(*p), deleter); 
     delete p; 
     p = nullptr; 
    } 
    S_ptr(S_ptr<T>& rhs) : ptr_(rhs.ptr_), counter_(rhs.counter_) { counter_->incre(); } 

    ~S_ptr() { delete counter_; } 

    // assignment 
    S_ptr& operator=(const S_ptr<T>& rhs) 
    { 
     auto temp = rhs.counter_; 
    temp->incre(); 
    counter_->decre(); 
    counter_ = temp; 
    ptr_ = rhs.ptr_; 
    return *this; 
} 
// .......... 

// private data member 
T* ptr_; 
Aux *counter_; 

};

+0

'這個 - > ref_count_' –

+1

。不是調試器,而是編譯器。 – Jarod42

回答

1

由於ref_count_是一個從屬名稱,你應該 「編譯時間,調試程序過程中」 使用

this->ref_count_ 

Aux::ref_count_ 
+0

它依賴於'AuxCounter'的模板參數嗎?怎麼樣?我知道[this](http://stackoverflow.com/a/993385/3552770),但這是不同的。請解釋。 – LogicStuff

+0

其實我也很困惑。通常,不需要爲了訪問從基類派生的成員而使用這個或作用域操作符。但爲什麼在這種情況下呢? –

+1

@AhSengFan - 全名是'S_ptr :: Aux',所以它依賴於'T'。 –

相關問題