首页 > 解决方案 > 指向指针的指针的 reinterpret_cast

问题描述

如果我有一个指向指针的派生类指针Derived**并希望将其转换为指向指针的基类指针Base**,则 usingstatic_cast<Base**>(ppd)无法编译,我被迫使用reinterpret_cast<Base**>,这似乎工作正常。是否有一个原因?在进行这种 reinterpret_cast 时,我应该记住任何警告吗?

下面是我写的一段示例代码:

struct Base {
    Base(int x0) : x(x0) {}
    int x;
};

struct Derived : Base {
    Derived(int x0, int y0): Base(x0), y(y0) {}
    int y;
};

void foo(Base** ppb) {
    *ppb = new Derived(5, 7);
}

void bar(Derived** ppd) {
    foo(reinterpret_cast<Base**>(ppd));
}

int main() {
    Base* pb = new Base(3);
    cout << pb->x << endl;
    delete pb;

    foo(&pb);
    cout << pb->x << ' ' << static_cast<Derived*>(pb)->y << endl;
    delete pb;

    Derived* pd = new Derived(2,4);
    cout << pd->x << ' ' << pd->y << endl;
    delete pd;

    bar(&pd);
    cout << pd->x << ' ' << pd->y << endl;
    delete pd;
}

标签: c++reinterpret-cast

解决方案


您实际上根本不需要reinterpret_cast

void bar(Derived** ppd) {
    Base *base;
    foo(&base);
    *ppd = static_cast<Derived*>(base);
}

推荐阅读