15

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

2 回答 2

25

如果允许,你可以这样写:

*bb = new Base;

最终会c指向. Base坏的。

于 2010-03-28T09:30:31.513 回答
1

指针是虚拟地址。通常你要对你用它做的事情负责。使用 msvc 2019。我可以将一个转换为基础,但不能转换为两个:

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
于 2020-05-10T08:41:28.353 回答