首页 > 代码库 > typeid, const_cast<Type>的使用

typeid, const_cast<Type>的使用

 

 1 #include <bits/stdc++.h> 2 using namespace std; 3  4 class A { 5     public : 6         void Show() { 7             cout << "A" << endl; 8         } 9 } ;10 11 class CC {12     public :13         void Show() {14             cout << "CC" << endl;15         }16 } ;17 18 class x {19     public :20         void Show() {21             cout << "x" << endl;22         }23 } ;24 25 class {26 } test;27 28 int main() {29     long long a, *b = 0;30     int *c;31     double *d;32     cout << (typeid(a) == typeid(long long)) << endl;33     cout << (typeid(a) == typeid(double)) << endl;34     b = &a;35     cout << (typeid(*b) == typeid(long long)) << endl;36     cout << typeid(b).name() << endl;37     cout << typeid(*b).name() << endl;38     cout << typeid(c).name() << endl;39     cout << typeid(*c).name() << endl;40     cout << typeid(d).name() << endl;41     cout << typeid(*d).name() << endl;42     A t;43     cout << typeid(t).name() << endl;44     CC s;45     cout << typeid(s).name() << endl;46     x *p;47     cout << typeid(p).name() <<   << typeid(*p).name() << endl;48     class {49     } temp;50     cout << typeid(temp).name() << endl;51     cout << typeid(test).name() << endl;52     class {53     } temp2;54     cout << typeid(temp2).name() << endl;55     class a {56     } temp3;57     cout << typeid(temp3).name() << endl;58     cout << typeid(long).name() << endl;59     unsigned long long l;60     cout << typeid(l).name() << endl;61     short z;62     cout << typeid(z).name() << endl;63     return 0;64 }
View Code

运行结果:

 1 1 2 0 3 1 4 Px 5 x 6 Pi 7 i 8 Pd 9 d10 1A11 2CC12 P1x 1x13 Z4mainEUt_14 5._12515 Z4mainEUt0_16 Z4mainE1a17 l18 y19 s20 21 22 // 在ubuntu 13.10下的运行结果
View Code

 

const_cast<Type>去除const或volatile限制:

 1 #include <bits/stdc++.h> 2 using namespace std; 3  4 char *Test(const char *s) { 5     char *t = const_cast<char *>(s); 6     *t = z; 7     return t; 8 } 9 10 int main() {11     const char *s1 = "abc";12     const char s2[] = "cba";13     //cout << Test(s1) << endl; // Run-Time Error14     cout << Test(s2) << endl;15     cout << s2 << endl;16     //cout << Test("ABC") << endl; // Run-Time Error17     return 0;18 }
View Code

 

 1 #include <bits/stdc++.h> 2 using namespace std; 3  4 void change(const int *pt) { 5     int *pc = const_cast<int *> (pt); 6     *pc = 100; 7 } 8  9 int main() {10     int pop1 = 18181;11     const int pop2 = 2000;12     cout << pop1 <<   << pop2 << endl;13     change(&pop1);14     change(&pop2);15     cout << pop1 <<   << pop2 << endl;16     return 0;17 }
View Code

 

 

——written by Lyon