危险的演员?

Oro*_*chi 1 c++ oop pointers

考虑一下:

#include <iostream>
using namespace std;
class A{
   protected:
       void some_function(int params)
       {
        //inside A: do something A related 
       }
};

class B: public A{
public:
    void call_some_function(int params)
    {
    some_function(params); // Simple call to A::some_function and NOTHING MORE.
    }
};


int main(int argc, char *argv[])
{
   A* a = new A();

   ((B*)(a))->call_some_function(20); // Is it OK ?
}
Run Code Online (Sandbox Code Playgroud)

此代码有效使用它有什么危险?

Kos*_*Kos 6

在C和C++中,它通常是未定义的行为(读作"非法但被编译器允许")通过指针或对另一种类型的对象的引用来取消引用一种类型的对象(少数例外,如通过指针访问一个基类).这称为严格别名规则.

在这里阅读更多内容:什么是严格别名规则?

您的代码通过指向类型B的指针访问类型A的对象,从而违反了此规则.


请注意,通常编译器无法验证您的静态强制转换(在您的情况下,C-cast等效于a static_cast).如果您不确定对象类型,dynamic_cast则在运行时验证转换是否合法,而不是static_cast仅在编译时检查转换并允许某些不正确的转换.