gpt4 book ai didi

c++ - 检查对象是否是基于基类的子类的实例

转载 作者:行者123 更新时间:2023-11-28 00:08:18 27 4
gpt4 key购买 nike

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

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

感谢帮助...

最佳答案

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

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

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

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

在 child 身上:

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

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

在 try block 之前创建子对象

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
}

关于c++ - 检查对象是否是基于基类的子类的实例,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34290870/

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