赞
踩
#include <stdio.h> int main() { int* p = new int; *p = 5; *p = *p + 10; printf("p = %p\n", p); printf("*p = %d\n", *p); delete p; p = new int[10]; for(int i=0; i<10; i++) { p[i] = i + 1; printf("p[%d] = %d\n", i, p[i]); } delete[] p; return 0; } /* E:\test>g++ 10-1.cpp E:\test>a p = 0000000000EB6E90 *p = 15 p[0] = 1 p[1] = 2 p[2] = 3 p[3] = 4 p[4] = 5 p[5] = 6 p[6] = 7 p[7] = 8 p[8] = 9 p[9] = 10 */
#include <stdio.h> int main() { int* pi = new int(1); // int* pa = new int[1]; float* pf = new float(2.0f); char* pc = new char('c'); printf("*pi = %d\n", *pi); printf("*pf = %f\n", *pf); printf("*pc = %c\n", *pc); delete pi; delete pf; delete pc; return 0; } /* *pi = 1 *pf = 2.000000 *pc = c */
#include <stdio.h> namespace First { int i = 0; } namespace Second { int i = 1; namespace Internal { struct P { int x; int y; }; } } int main() { using namespace First; using Second::Internal::P; printf("First::i = %d\n", i); printf("Second::i = %d\n", Second::i); P p = {2, 3}; printf("p.x = %d\n", p.x); printf("p.y = %d\n", p.y); return 0; } E:\test>g++ 10-3.cpp E:\test>a First::i = 0 Second::i = 1 p.x = 2 p.y = 3
#include <stdio.h> typedef void(PF)(int); struct Point { int x; int y; }; int main() { int v = 0x12345; PF* pf = (PF*)v; char c = char(v); Point* p = (Point*)v; pf(5); printf("p->x = %d\n", p->x); printf("p->y = %d\n", p->y); return 0; } //error
#include <stdio.h> void static_cast_demo() { int i = 0x12345; char c = 'c'; int* pi = &i; char* pc = &c; c = static_cast<char>(i); //pc = static_cast<char*>(pi);//error: invalid static_cast from type 'int*' to type 'char*' } void const_cast_demo() { const int& j = 1; int& k = const_cast<int&>(j); const int x = 2; int& y = const_cast<int&>(x); //int z = const_cast<int>(x);//error: invalid use of const_cast with type 'int', which is not a pointer, reference, nor a pointer-to-data-member type k = 5; printf("k = %d\n", k); printf("j = %d\n", j); y = 8; printf("x = %d\n", x); printf("y = %d\n", y); printf("&x = %p\n", &x); printf("&y = %p\n", &y); } void reinterpret_cast_demo() { int i = 0; char c = 'c'; int* pi = &i; char* pc = &c; pc = reinterpret_cast<char*>(pi); pi = reinterpret_cast<int*>(pc); pi = reinterpret_cast<int*>(i); //c = reinterpret_cast<char>(i); // error: invalid cast from type 'int' to type 'char' } void dynamic_cast_demo() { int i = 0; int* pi = &i; //char* pc = dynamic_cast<char*>(pi);//error: cannot dynamic_cast 'pi' (of type 'int*') to type 'char*' (target is not pointer or reference to class) } int main() { static_cast_demo(); const_cast_demo(); reinterpret_cast_demo(); dynamic_cast_demo(); return 0; }
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。