2016-07-12 117 views
2

對於下面的代碼:恆指針參考

class Foo { 
private: 
    int var; 
    int* var_ptr; 

public: 
    Foo() : var_ptr(&var), var_ptr_ref(var_ptr) {} 
    int*& var_ptr_ref; // Read only access to var and var_ptr 
}; 

是否有可能使指針常量和實際的變量恆定時經由var_ptr_ref訪問?

回答

2

嘗試宣告var_ptrconst intvar_ptr_refconst int * const &

class Foo { 
private: 
    int var; 
    const int * var_ptr; 

public: 
    Foo() : var_ptr(&var), var_ptr_ref(var_ptr) {} 
    const int * const & var_ptr_ref; 
}; 
+0

我得到一個錯誤'結合參考成員「var_ptr_ref」爲構造線臨時variable'。 – user1135541

+0

@ user1135541適合我。 http://ideone.com/PqKXDc –

+0

@ user1135541至少我的VS2015很樂意編譯它。 – AlexD