gpt4 book ai didi

c++ - 当目标指针不是基类的类型时,为什么允许dynamic_cast为多态类生成空指针?

转载 作者:行者123 更新时间:2023-12-01 14:39:59 25 4
gpt4 key购买 nike

考虑以下程序

#include <iostream>
#include <iomanip>

struct A
{
};

struct C
{
};

int main()
{
C *pc = nullptr;

A *pa1 = dynamic_cast<A *>( pc );

std::cout << "pa1 == nullptr is " << std::boolalpha << ( pa1 == nullptr ) << '\n';

A *pa2 = pc;

std::cout << "pa2 == nullptr is " << std::boolalpha << ( pa2 == nullptr ) << '\n';
}

对于两个指针声明pa1和pa2,编译器都会报告一个错误,指出不允许进行此类初始化。

例如,铛HEAD 10.0.0编译器发出以下错误。
prog.cc:19:14: error: 'C' is not polymorphic
A *pa1 = dynamic_cast<A *>( pc );
^ ~~
prog.cc:23:8: error: cannot initialize a variable of type 'A *' with an lvalue of type 'C *'
A *pa2 = pc;
^ ~~
2 errors generated.

现在,让C类成为多态类。
#include <iostream>
#include <iomanip>

struct A
{
};

struct C
{
virtual ~C() = default;
};


int main()
{
C *pc = nullptr;

A *pa1 = dynamic_cast<A *>( pc );

std::cout << "pa1 == nullptr is " << std::boolalpha << ( pa1 == nullptr ) << '\n';

A *pa2 = pc;

std::cout << "pa2 == nullptr is " << std::boolalpha << ( pa2 == nullptr ) << '\n';
}

而且只有第二个声明会产生错误。 dynamic_cast有效。
rog.cc:22:8: error: cannot initialize a variable of type 'A *' with an lvalue of type 'C *'
A *pa2 = pc;
^ ~~
1 error generated.

允许对 dynamic_cast进行指针转换的原因是什么?

最佳答案

What is the reason of that such a conversion of pointers for the dynamic_cast is allowed?



因为 dynamic_cast在运行时运行,到那时发布编译器错误为时已晚。

如果转换失败, dynamic_cast返回 nullptr。您需要检查一下,然后在需要时进行处理。

关于c++ - 当目标指针不是基类的类型时,为什么允许dynamic_cast为多态类生成空指针?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59849453/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com