加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

C中不同类树之间的转换

发布时间:2020-12-16 10:30:27 所属栏目:百科 来源:网络整理
导读:下面的代码似乎适用于我试过的编译器(clang,g,Linux和Mac OS),但它是否保证总能做到人们所期望的? struct A { virtual void foo() = 0;};struct A2 { virtual void foo() = 0;};struct B : public A2 { void foo() { printf("testn"); }};int main() { B*
下面的代码似乎适用于我试过的编译器(clang,g,Linux和Mac OS),但它是否保证总能做到人们所期望的?

struct A {
  virtual void foo() = 0;
};

struct A2 {
  virtual void foo() = 0;
};

struct B : public A2 {
  void foo() {
    printf("testn");
  }
};

int main() {
  B* b = new B;
  ((A*)b)->foo();
}

我意识到这是不好的做法,不应该这样做,但它一般是否有效?

解决方法

实践并不坏:它不起作用.它会做点好事.不太可能,崩溃.由于您正在调用 unspecified behaviour,因此全部允许.编辑您可以查阅编译器技术文档(请参阅ABI)以查找您可能依赖的特定于编译器的扩展.

尝试使用

static_cast<A*>(b)    // invalid static cast (compile error)
dynamic_cast<A*>(b)   // returns null pointer value (runtime)

你在做什么是有效的

> reinterpret_cast< A *>(b)

并且结果完全由您自己负责实施定义.

编辑纳瓦兹:相关标准段落:§5.2.10,条款

7. A pointer to an object can be explicitly converted to a pointer to a different object type.69 When a
prvalue v of type “pointer to T1” is converted to the type “pointer to cv T2”,the result is static_cast<cv T2*>(static_cast<cv void*>(v)) if both T1 and T2 are standard-layout types (3.9) and the alignment
requirements of T2 are no stricter than those of T1. Converting a prvalue of type “pointer to T1” to the type “pointer to T2” (where T1 and T2 are object types and where the alignment requirements of T2 are no stricter than those of T1) and back to its original type yields the original pointer value. The result of any other such pointer conversion is unspecified.

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读