#include <iostream> int main() { double d = 10.2; int i = static_cast<int>(d); std::cout << "d:" << d << " i:" << i << std::endl; }
d:10.2 i:10
static_cast是一个模板函数,如上使用就可以完成类型的转换,
1 2 3 4 5 6 7 8 9 10 11 12 13
#include <iostream> int main() { //double d = 10.2; //int i = static_cast<int>(d); //std::cout << "d:" << d << " i:" << i << std::endl; int i = 10; int *p = &i; int address = static_cast<int>(p); }
invalid static_cast from type 'int*' to type 'int'
#include <iostream> int main() { int i = 10; double d; int* p = &i; //将指针强转为整形 long long address = reinterpret_cast<long long>(p); std::cout << p << " " << address; }
0x61fe0c 6422028
const_cast
const_cast可以完成从const对象到non-const对象的转换.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16
#include <iostream> int main() { const int i = 10; std::cout << i << std::endl; int& r = const_cast<int&>(i); r = 11; std::cout << i << std::endl; std::cout << r << std::endl; const int a = 2; int *p = const_cast<int*>(&a); *p = 3;
#include <iostream> class Parent { public: virtual void Func() {
} int s = 10; }; class Son : public Parent { public: int s = 11; }; int main() { Parent* p = new Parent; std::cout << p->s << std::endl; Son* s = dynamic_cast<Son*>(p); if(s == nullptr) { std::cout << "change error" << std::endl; return -1; } std::cout << s->s << std::endl; }
#include <iostream> class Test { public: Test(int test) :_test(test) { std::cout << "construct" << std::endl; } private: int _test; }; int main() { Test test = 10; }
construct
禁用:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16
#include <iostream> class Test { public: explicit Test(int test) :_test(test) { std::cout << "construct" << std::endl; } private: int _test; }; int main() { Test test = 10;//编译不过 }
近期评论