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

时间:2010-03-28 09:25:32

标签: c++ inheritance pointers subtyping

关于以下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;
}

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

error: invalid conversion from ‘Child**’ to ‘Base**’

我的问题分为两部分:

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

2 个答案:

答案 0 :(得分:19)

如果允许,可以写下:

*bb = new Base;

c最终会指向Base的实例。坏。

答案 1 :(得分:1)

指针是虚拟地址。通常,您应对使用该工具负责。使用msvc2019。我可以将一个转换为基础,但不能转换为两个:

example 1:

int p;
int *p1 = &p;
int **p2 = &p1; //OK

example 2:

struct xx {};
struct yy : public xx {};

yy p;
yy *p1 = &p;
xx **p2 = &p1; //Just a strange error

example 3:

struct xx {};
struct yy : public xx {};

yy p;
xx *p1 = &p; 
xx **p2 = &p1; //OK
相关问题