c – 地址,reinterpret_cast和多重继承

前端之家收集整理的这篇文章主要介绍了c – 地址,reinterpret_cast和多重继承前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
有人可以解释以下代码的行为吗?

>为什么在第一种情况下我们有b = 3,即b2 ==& d是真的?
>为什么在案例2中可以确定?我打印了b2和d的地址,它们是不同的.

#include <iostream>

using namespace std;

class A
{
public:
    A() : m_i(0) { }

protected:
    int m_i;
};

class B
{
public:
    B() : m_d(0.0) { }

protected:
    double m_d;
};

class C
    : public A,public B
{
public:
    C() : m_c('a') { }

private:
    char m_c;
};

int main()
{
    C d;
    B *b2 = &d;

    cout << &d << endl;
    cout << b2 << endl;

    const int b = (b2 == &d) ? 3 : 4; ///Case1: b = 3;
    const int c = (reinterpret_cast<char*>(b2) == reinterpret_cast<char*>(&d)) ? 3 : 4; //Case 2:  c = 4;

    std::cout  << b << c << std::endl;

    return 0;
}

解决方法

d为C类型.当将指针C转换为B的指针时,将其调整为指向C的B子对象(如果不需要B,则需要这样的调整,通常需要多个继承,A和C之间的A将继承自A).因此,在分配和比较时间,进行调整.

在另外两个时间,& d被转换为void *(隐含地)或者char *(有一个reinterpret_cast),并且没有调整完成(你明确地询问没有调整reinterpret_cast,没有理由做一个调整当转换为void *时,只会使往返行程复杂化,没有什么好的理由,您再次对A有类似的结果,所以表示方式是不同的.

BTW,如果您已经使用了reinterpret_cast< B *>(& d),则不会再进行任何调整,但将结果作为B *使用会导致问题的快速发展.

猜你在找的C&C++相关文章