const_cast使用

来源:互联网 发布:windows 10关闭快捷键 编辑:程序博客网 时间:2024/06/06 02:21


 9class B 10 { 11 public: 12         B(int a):val(a) 13         { 14         } 15  16         ~B() 17         { 18         } 19  20         int val; 21 }; 22  23 template<class T> 24 T& remove_const(const T& val) {return const_cast<T&>(val);} 25  26  27  28 class A 29 { 30 public: 31         A() 32         { 33  34         } 35  36         ~A() 37         { 38  39         } 40  41         template<class T> 42         void Put(T& t) 43         { 44                 B& b = remove_const(t); 45                 b.val = 2; 46         } 47  48  49 private: 50         B* ptr; 51 };


 58 int main() 59 { 60         A a; 61         const B b(1); 62         a.Put(b); 63  64         const int i = 2; 65         ++remove_const(i); 66         cout<<i<<endl; 67         cout<<b.val<<endl; 68         return 0; 69 }

类对象可改变值,内置类型无法改变值;

0 0
原创粉丝点击