如何检查两个对象是否继承自同一个基类?
我正在尝试重写 C++ .NET 中的 Object::Equals,但遇到了一些困难
virtual bool IState::Equals(Object^ o) override{
if (o->GetType() == IState::typeid){
IState^ s = (IState^) o;
if (s->type == this->type &&
s->target_state == this->target_state &&
s->current_state == this->current_state){
return true;
}
else{
return false;
}
}
return false;
}
如果 o 是且 IState,此代码可以正常工作。 但是,我从 IState 继承了 State。 如果我传递具有相同内容的 State,我希望 Equals 函数返回 true。
我知道 State 与 IState 不同,但是是否有一个运算符可以让我检查它们是否从同一个基类继承? 也许重载操作符 typeid可能有帮助,但这似乎很麻烦
I'm trying to override Object::Equals in C++ .NET but I'm running into some difficulties
virtual bool IState::Equals(Object^ o) override{
if (o->GetType() == IState::typeid){
IState^ s = (IState^) o;
if (s->type == this->type &&
s->target_state == this->target_state &&
s->current_state == this->current_state){
return true;
}
else{
return false;
}
}
return false;
}
This code works fine if o is and IState. However, I inherit from IState with State. I'd like my Equals function to return true if I pass a State with the same content.
I get that State is not the same as IState, but is there an operator which will allow me to check if they inherit from the same base class?
Maybe overloading the operator typeid might help, but it seems like a lot of trouble for that
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
使用反射是一种选择吗? 如果是这样,请查看 Type::IsAssignableFrom() 方法,以及 Type::BaseType 财产。
Is using reflection an option? If so, take a look at the Type::IsAssignableFrom() method, and the Type::BaseType property.
正确的方法是使用dynamic_cast,并检查nullptr:
您使用的C风格强制转换(避免那些顺便说一句)实际上会执行safe_cast,这会在失败时抛出InvalidCastException,因此您必须显式地拼写出dynamic_cast。
The correct way to do this is to use dynamic_cast, and check for nullptr:
C-style cast (avoid those BTW) that you have used will actually do a safe_cast, which throws InvalidCastException on failure, so you have to spell out dynamic_cast explicitly.
好的,我设法让它工作,
我在 ->GetType() 之后缺少 ->BaseType()
这是工作版本,
谢谢大家的时间、支持和奉献 =)
Ok I managed to get it to work
I was missing the ->BaseType() after the ->GetType()
here is the working version
thank you all for your time, support and devotion =)
使用 typeid 运算符怎么样?
http://msdn.microsoft.com/en-us /library/fyf39xec(VS.80).aspx
How about using the typeid operator?
http://msdn.microsoft.com/en-us/library/fyf39xec(VS.80).aspx