现在的位置: 首页 > 综合 > 正文

static_cast与c风格的强制类型转换

2014年11月10日 ⁄ 综合 ⁄ 共 528字 ⁄ 字号 评论关闭

class A
{
    int a;
};

class B
{
    int b;
};

class C : public A
{
    int c;
};

int main()
{
    B b;
    C c;
    
    A* p1 = (A*) &b; // 这句是c风格的强制类型转换,编译不会报错,留下了隐患
    A* p2 = static_cast<A*>(&b); // static_cast在编译时进行了类型检查,直接报错
    A* p3 = dynamic_cast<A*>(&b);
    
    A* p4 = (A*) &c;
    A* p5 = static_cast<A*>(&c);
    A* p6 = dynamic_cast<A*>(&c);
    
    return 0;
}

/*

编译直接报错:

cast.cpp: In function 'int main()':
cast.cpp:22:31: error: invalid static_cast from type 'B*' to type 'A*'
cast.cpp:23:32: error: cannot dynamic_cast '& b' (of type 'class B*') to type 'class A*' (source type is not polymorphic)

*/

应使用static_cast取代c风格的强制类型转换,较安全。

抱歉!评论已关闭.