【发布时间】: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<Child *>(ex.subject)) -
ex.subject在catch块中无效,因为它已被破坏。所以它导致了未定义的行为 -
@Danh 我有更复杂的代码,我想在其中使用
child变量 - 这只是一个示例。