根据Base类检查对象是否是Child类的内容

时间:2015-12-15 13:45:42

标签: c++ pointers exception

我试图检查对象是否是某个类的实例,但它不起作用。这是我的简化代码:

class Base
{
public:
    Base() { }
    virtual ~Base() { }
};

class Child : public Base
{
public:
    Child(int something) { }

    void Method()
    {
        throw Exception(this);
    }
};

class Exception
{
public:
    Base* subject;
    Exception(Base* base) : subject(base) { }
};

/* ---------------------------------------------------- */

try
{
    Child ch(1);
    ch.Method();
}
catch (Exception& ex)
{
    // the exception is thrown in Child class
    // therefore pointer to Child object is passed as an argument
    // to Exception's contructor so I'd expect folowing statement to be true
    // but it isn't

    if (Child *child = dynamic_cast<Child *>(ex.subject))
        std::cout << "subject of the exception is Child" << std::endl;
    else
        std::cout << "subject of the exception is just Base" << std::endl;
}

感谢您的帮助...

2 个答案:

答案 0 :(得分:2)

ex.subject在catch块中无效,因为它已被破坏。所以它导致了未定义的行为。

我在这里看到两个解决方案:

1)如果您只是需要知道哪个类导致错误:

class Exception
{
public:
    std::string subject;
    Exception(const std::string &base) : subject(base) { }
};

在孩子身上:

void Method()
{
    throw Exception("Child");
}

2)如果您需要抛出异常的对象:

您在try块

之前创建子对象
Child ch(1);
try
{
    ch.Method();
}
catch (Exception& ex)
{
    // the exception is thrown in Child class
    // therefore pointer to Child object is passed as an argument
    // to Exception's contructor so I'd expect folowing statement to be true
    // but it isn't

    //Do something with ch
}

答案 1 :(得分:1)

要修复您的示例,请将对象的构造放在&#34;尝试&#34;块。如果在块内声明了对象析构函数,则调用它们。

Child ch(1);
try
{
    ch.Method();
}