相关疑难解决方法(0)

派生类和基类之间的指针到指针的转换?

关于以下C++程序:

class Base { };

class Child : public Base { };

int main()
{   
    // Normal: using child as base is allowed
    Child *c = new Child();
    Base *b = c;

    // Double pointers: apparently can't use Child** as Base**
    Child **cc = &c;
    Base **bb = cc;

    return 0;
}
Run Code Online (Sandbox Code Playgroud)

GCC在最后一个赋值语句中产生以下错误:

error: invalid conversion from ‘Child**’ to ‘Base**’
Run Code Online (Sandbox Code Playgroud)

我的问题分为两部分:

  1. 为什么没有从Child**到Base**的隐式转换?
  2. 我可以使这个例子使用C风格的演员或者reinterpret_cast.使用这些演员表意味着抛弃所有类型的安全.有没有什么我可以添加到类定义中来隐式地转换这些指针,或者至少以允许我使用的方式表达转换static_cast

c++ inheritance pointers subtyping

12
推荐指数
1
解决办法
3549
查看次数

标签 统计

c++ ×1

inheritance ×1

pointers ×1

subtyping ×1