【问题标题】:Check if object is instenace of Child class based on Base class检查对象是否是基于基类的子类的实例
【发布时间】:2015-12-15 13:45:41
【问题描述】:

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

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;
}

感谢您的帮助...

【问题讨论】:

  • 你为什么不写if (dynamic_cast&lt;Child *&gt;(ex.subject))
  • ex.subjectcatch 块中无效,因为它已被破坏。所以它导致了未定义的行为
  • @Danh 我有更复杂的代码,我想在其中使用 child 变量 - 这只是一个示例。

标签: c++ pointers exception


【解决方案1】:

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
}

【讨论】:

  • 谢谢,但是(根据第二个选项)如果 Child 的构造函数抛出异常怎么办?
  • @MartinHeralecký 您可以创建从构造函数抛出的第二个异常类。第二个例外基于我的第一个示例
【解决方案2】:

要修复您的示例,请将对象的构造放在“try”块之前。如果在块内声明了对象析构函数,则会调用它。

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

【讨论】:

    猜你喜欢
    • 2013-05-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-01-08
    • 1970-01-01
    • 2012-03-01
    • 2021-11-20
    相关资源
    最近更新 更多