ICode9

精准搜索请尝试: 精确搜索
首页 > 其他分享> 文章详细

转换为不同的基类会产生不同的结果. C

2019-08-28 05:05:39  阅读:236  来源: 互联网

标签:reinterpret-cast static-cast c casting inheritance


也许我的问题没有完美形成,但我的代码将使一切都清楚.

#include <iostream>
using namespace std;

struct A{int n;};
struct B{int n;};
struct C : A, B{};

int main()
{
    C c;
    C* pc = &c;

    std::cout<<"TEST1"<<std::endl;
    cout << static_cast<B*>(pc) << "\n";
    cout << reinterpret_cast<B*>(pc)<<"\n\n";

    std::cout<<"TEST2"<<std::endl;
    cout << static_cast<A*>(pc) << "\n";
    cout << reinterpret_cast<A*>(pc)<<"\n";
}

输出是:

TEST1
0042F830
0042F82C

TEST2
0042F82C
0042F82C

我知道使用reinterpret_cast是错误的设计.我不是在考虑设计,但行为是困扰我的.
任何人都可以解释为什么铸造不同的方式第一次给出不同的结果,但第二次相同的结果?

解决方法:

定义类也意味着定义内存布局.在其最简单的形式中,成员连续布局,例如,

struct A {
    int n;
};

并在记忆中

| Address  | Size | Member |
|----------+------+--------+
| 0042F82C | 4    | n      |

基类也是如此

struct C : A, B {
};

潜在的内存布局

| Address  | Size | Member |
|----------+------+--------+
| 0042F82C | 4    | A::n   |
| 0042F830 | 4    | B::n   |

现在,您有一个指向类型为C的对象的指针pc.使用static_cast会考虑对象中成员和基类的布局.

因此,您可以获得A或B部件的正确地址.

在另一侧使用reinterpret_cast,只需重用指针并假装它指向另一种类型.

Explanation

Unlike static_cast, but like const_cast, the reinterpret_cast expression does not compile to any CPU instructions. It is purely a compiler directive which instructs the compiler to treat the sequence of bits (object representation) of expression as if it had the type new_type.

这就是为什么你得到相同的地址值的原因.

标签:reinterpret-cast,static-cast,c,casting,inheritance
来源: https://codeday.me/bug/20190828/1748355.html

本站声明: 1. iCode9 技术分享网(下文简称本站)提供的所有内容,仅供技术学习、探讨和分享;
2. 关于本站的所有留言、评论、转载及引用,纯属内容发起人的个人观点,与本站观点和立场无关;
3. 关于本站的所有言论和文字,纯属内容发起人的个人观点,与本站观点和立场无关;
4. 本站文章均是网友提供,不完全保证技术分享内容的完整性、准确性、时效性、风险性和版权归属;如您发现该文章侵犯了您的权益,可联系我们第一时间进行删除;
5. 本站为非盈利性的个人网站,所有内容不会用来进行牟利,也不会利用任何形式的广告来间接获益,纯粹是为了广大技术爱好者提供技术内容和技术思想的分享性交流网站。

专注分享技术,共同学习,共同进步。侵权联系[81616952@qq.com]

Copyright (C)ICode9.com, All Rights Reserved.

ICode9版权所有