c++ - static_cast 怀疑

标签 c++ casting visual-c++-2010-express

#include <iostream>
class A
{
public:
    A()
    {
        std::cout << "\n A_Constructor \t" << this <<std::endl;
    }
    void A_Method()
    {
        std::cout <<"\n A_Method \t" << this <<std::endl;
    }
};
class B:public A
{
public:
    B()
    {
        std::cout <<"\n B_Constructor \n";
    }
    void B_Method()
    {
        std::cout <<"\n B_Method \t" << this <<std::endl;
    }
};

int main()
{
    A *a_obj = new A;
    B *b_obj = static_cast<B*> (a_obj);  // This isn't safe.
    b_obj->B_Method();      
    getchar();
    return 0;
}

输出:

A_Constructor 001C4890
B_Method 001C4890

由于类型转换不涉及运行时检查,static_cast 不安全。但是在这个例子中,我得到了我什至没有想到的结果。由于没有调用 B::B(),它的任何成员都不能被 b_obj 调用。尽管如此,我还是得到了输出。

在这个简单的例子中,虽然已知它不安全,但我可能已经成功了。我的疑问是 -

  • 虽然没有调用 B::B(),但我如何能够访问 B 类 成员函数。
  • 有人可以提供一个示例,说明这是不安全的并且可能会出错(尽管我之前给出的示例可能是一个不好的示例,但更好)。

我是在 Visual Studio 2010 上完成的,并设置了 \Wall 选项。

最佳答案

这是未定义的行为。有时 UB 会导致崩溃。有时它似乎“有效”。你不应该这样做是对的,即使在这种情况下发生的坏事较少。

关于c++ - static_cast 怀疑,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4649755/

相关文章:

c# - 为什么 SQL float 与 C# float 不同

c# - 继承 Linq to SQL 类并转换 linq 查询的结果

c++ - C++ 中的 For 循环 - 变量未正确递增

c++ - 在 VS2013 中使用 VS2008 (v90) C++ 工具集?

c++ - 类类型错误 C++ with struct

c++ - 为什么 wcslen 在 argv[1] 上计算 1 个额外字符?

c++ - 将 void* 转换为动态类型

visual-c++ - 使用 Visual C++ Express 2010 时找不到 atlbase.h

c++ - 在 operator delete[] 中取消析构函数调用