C++常用到的口试题
题目: 关于C++中, 四种范例转换的要害字, 的详解, 也可以给出代码, 判定输出 或 判定哪些代码有误.
谜底及典型如下:
四种要害字: const_cast, 常量性转除;dynamic_cast, 向下安详转型; reinterpret_cast, 从头表明转型; static_cast, 静态转型;
1. const_cast, 常量性转除:
主要对变量的常量性(const)举办操纵, 移除变量的常量性, 即可以被很是量指向和引用, 详见代码;
2. dynamic_cast, 向下安详转型:
主要应用于担任体系, 可以由 "指向派生类的基类部门的指针", 转换"指向派生类"或"指向兄弟类";
static_cast只能转换为"指向派生类";
3. reinterpret_cast, 从头表明转型:
主要是对2进制数据举办从头表明(re-interpret),不改变名目, 而static_cast会改变名目举办表明;
如由派生类转换基类, 则从头表明转换, 不改变地点, 静态转换改变地点;
4. static_cast, 静态转型:
主要是数据范例的转换, 还可以用于担任;
代码如下:
/* * cppprimer.cpp * * Created on: 2014.2.10 * Author: Spike */ /*eclipse cdt, gcc 4.8.1*/ #include/*常量性移除指针详解*/ struct S { S() : value(0) {} int value; }; void CastConst (void) { const S s; std::cout << "s.value = " << s.value << std::endl; //S* ps = &s; //error, 指向常量 S* ps = const_cast(&s); ps->value = 1; std::cout << "s.value = " << s.value << std::endl; //S& rs = s; //error, 引用常量 S& rs = const_cast(s); rs.value = 2; std::cout << "s.value = " << s.value << std::endl; } /*安详向下转型*/ struct B /*基类B*/ { virtual void f() { std::cout << "Base::f" << std::endl; } void thisf() { std::cout << "Base::thisf" << std::endl;} virtual ~B() {} }; struct B2 /*基类B2*/ { virtual void g() { std::cout << "Base2::g" << std::endl; } void thisg() { std::cout << "Base2::thisg" << std::endl;} virtual ~B2() {} }; struct D : public B, public B2 /*派生类D*/ { virtual void f() { std::cout << "Derived::f" << std::endl; } virtual void g() { std::cout << "Derived::g" << std::endl; } virtual ~D() {} }; void CastDynamic (void) { B* pB_D = new D; pB_D->f(); //pD->g(); //error, 只包括B部门 D *pD_D = dynamic_cast(pB_D); //转换为派生类 pD_D->g(); B2* pB2_D = dynamic_cast(pB_D); //转换为兄弟类 pB2_D->g(); D *pD_Ds = static_cast(pB_D); pD_Ds->g(); //B2* pB2_Ds = static_cast(pB_D); //error, 不能转换为兄弟类 } /*从头表明转型*/ struct rA { int m_a; }; struct rB { int m_b; }; struct rC : public rA, public rB {}; void CastReinterpret (void) { int *i= new int; *i = 10; std::cout << "*i = " << *i << std::endl; std::cout << "i = " << i << std::endl; double *d=reinterpret_cast(i); std::cout << "*d = " << *d << std::endl; std::cout << "d = " << d << std::endl; rC c; std::cout << "&c = " << &c << std::endl << "reinterpret_cast(&c) = " <<reinterpret_cast(&c) << std::endl << "static_cast(&c) = " << static_cast(&c) << std::endl << "reinterpret_cast(&c) = " <<reinterpret_cast(&c) << std::endl << "static_cast(&c) = " << static_cast(&c) << std::endl << std::endl; } int main (void) { std::cout << std::endl << "常量性转除:" << std::endl; CastConst(); std::cout << std::endl << "安详向下转型:" << std::endl; CastDynamic(); std::cout << std::endl << "从头表明转型:" << std::endl; CastReinterpret(); }
输出:
常量性转除: s.value = 0 s.value = 1 s.value = 2 安详向下转型: Derived::f Derived::g Derived::g Derived::g 从头表明转型: *i = 10 i = 0x471718 *d = 2.55917e-307 d = 0x471718 &c = 0x22feb0 reinterpret_cast(&c) = 0x22feb0 static_cast(&c) = 0x22feb4 reinterpret_cast(&c) = 0x22feb0 static_cast(&c) = 0x22feb0