错误:无法dynamic_cast ...(目标不是指针或引用) [英] error: cannot dynamic_cast ... (target is not pointer or reference)

查看:391
本文介绍了错误:无法dynamic_cast ...(目标不是指针或引用)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在学习C ++中的异常处理并遇到问题。代码如下:

I'm learning exception handling in C++ and run into a problem. Here's the code:

#include<iostream>
#include<exception>

using namespace std;

class A
{
public:
    virtual void f(void){}
};

class AA:public A
{
public:
    void aa(void){};

};

int main(void)
{

    A a;
    try
    {
        dynamic_cast<AA>(a).aa();
    }
    catch(exception ex)
    {
        cout<<"["<<ex.what()<<"]"<<endl;
    }
    return 0;
}

所以我认为try catch将允许函数执行并向我显示异常的内容,但是我的编译器没有编译它。我在GNU GCC中使用代码块。请帮助我,告诉我如何使代码按预期运行。

So I thought the try catch will allow the function to execute and show me the content of the exception, but my compiler does not compile it. I'm using codeblock with GNU GCC. Please help me and show me what I need to do to get the code run as I intended. thanks a lot.

推荐答案

dynamic_cast 只能转换为指针值

从C ++标准的$ 5.2.7 / 1起。

From $5.2.7/1 of the C++ Standard.


表达式dynamic_cast<的结果; T>(v)是将表达式v转换为类型T的结果。T应该是完整类类型的指针或引用,或者是 cv void的指针。

The result of the expression dynamic_cast< T >(v) is the result of converting the expression v to type T. T shall be a pointer or reference to a complete class type, or "pointer to cv void."

为了使 dynamic_cast 在无法转换对象时引发异常,您需要转换为引用。将其更改为以下内容:

In order for dynamic_cast to throw an exception when the object cannot be converted you need to cast to a reference. Change it to the following:

dynamic_cast<AA&>(a).aa();
//           ^^^ cast to reference.

Johnsyweb 指出 dynamic_cast 将始终抛出 std :: bad_cast ,但转换失败。尽管 std :: bad_cast 是从 std :: exception 派生的,但最好使用最好的异常符合预期的失败条件。这样可以防止无意间将其他错误解释为转换失败。

As Johnsyweb pointed out dynamic_cast will always throw std::bad_cast when the conversion fails. Although std::bad_cast is derived from std::exception it is always a good idea to use the exception which best fits the expected fail condition. This prevents inadvertently interpreting other errors as an unsuccessful cast.

要将其应用于您的示例,它可能看起来像下面的代码。

To apply this to your example it might look like the code below.

#include <iostream>
#include <typeinfo> // std::bad_cast

class A
{
public:
    virtual void f(void){}
};

class AA:public A
{
public:
    void aa(void){};
};

int main(void)
{
    A a;

    try
    {
        dynamic_cast<AA&>(a).aa();
    }
    catch(const std::bad_cast& ex)
    {
        std::cout << "["<<ex.what()<<"]" << std::endl;
    }
    return 0;
}

[注意,使用命名空间std做类似的操作;强烈建议,因为它可能导致与全局命名空间中的标识符冲突。我已在上面的示例中将其删除。]

[Note, doing things like using namespace std; is strongly discouraged as it can cause conflicts with identifiers in the global namespace. I have removed it in the example above.]

这篇关于错误:无法dynamic_cast ...(目标不是指针或引用)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆