#include<stdio.h> main() { double d = (double) 5; printf("%f\n", d); int i = (int) 5.4; // OK printf("%d\n", i); int i2 = (int) (5.4); // OK printf("%d\n", i2); int i3 = int (5.4); // Error printf("%d\n", i3); double result = (double) 4 / 5; // OK printf("%f\n", result); }
#include<iostream> classA { int x = 0; public: A(int x) { this->x = x; } intgetX(){ return x; } }; classB { int x = 0, y = 0; public: B(A a) { x = a.getX(); y = a.getX(); } voidgetXY(int &x, int &y){ x = this->x; y = this->y; } }; intmain(){ A a(10); B b = a; // 隐式转换 int x, y; b.getXY(x, y); std::cout << "x: " << x << " y: " << y << std::endl; return0; }
typedefunsignedchar BYTE; voidf(){ int i = 65; float f = 2.5; char ch = static_cast<char>(i); // int to char double dbl = static_cast<double>(f); // float to double i = static_cast<BYTE>(ch); }
#include<iostream> classB { public: int num = 5; }; intmain(){ usingnamespacestd; const B b1;
b1.num = 10; // Error: assignment of member 'B::num' in read-only object cout << b1.num << endl;
B b2 = const_cast<B>(b1); // Error: invalid use of const_cast with type 'B', // which is not a pointer, reference, nor a pointer-to-data-member type b2.num = 15; cout << b1.num << endl;
B *b3 = const_cast<B *>(&b1); // OK b3->num = 20; cout << b1.num << endl;
B &b4 = const_cast<B &>(b1); // OK b4.num = 25; cout << b1.num << endl; }
classB { }; classC :public B { }; classD :public C { }; voidf(D* pd){ C* pc = dynamic_cast<C*>(pd); // ok: C is a direct base class // pc points to C subobject of pd B* pb = dynamic_cast<B*>(pd); // ok: B is an indirect base class // pb points to B subobject of pd }
#include<iostream> classB {virtualvoidf(){}}; classD :public B {};
intmain(){ B* b = new D; B* b2 = new B;
D* d = dynamic_cast<D*>(b); if (d == nullptr) { std::cout << "null pointer on first type-casting." << std::endl; } D* d2 = dynamic_cast<D*>(b2); if (d2 == nullptr) { std::cout << "null pointer on second type-casting." << std::endl; } return0; }
显然,输出结果是
1
null pointer on second type-casting.
再来看一个子类之间转换的例子:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19
#include<iostream> classA { public: int num = 5; virtualvoidf(){} };
classB :public A {};
classD :public A {};
intmain(){ B *b = new B; b->num = 10; D *d1 = static_cast<D *>(b); // Error: invalid static_cast from type 'B*' to type 'D*' D *d2 = dynamic_cast<D *>(b); // OK std::cout << (d2 == nullptr) << std::endl; // 1 delete b; }
一个比较复杂的例子:
1 2 3 4 5 6 7 8 9 10 11
classA {virtualvoidf();}; classB :public A {virtualvoidf();}; classC :public A { }; classD {virtualvoidf();}; classE :public B, public C, public D {virtualvoidf();}; voidf(D* pd){ E* pe = dynamic_cast<E*>(pd); B* pb = pe; // upcast, implicit conversion A* pa = pb; // upcast, implicit conversion }