2016-07-12 116 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