如何检查对象的类型是否是C ++中的特定子类? [英] How do I check if an object's type is a particular subclass in C++?

查看:127
本文介绍了如何检查对象的类型是否是C ++中的特定子类?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我一直在使用typeid(),但我不知道如何问,如果该类型是另一个类的子类(顺便说一下,是抽象的)

I was thinking along the lines of using typeid() but I don't know how to ask if that type is a subclass of another class (which, by the way, is abstract)

推荐答案

你真的不应该。如果你的程序需要知道一个对象是什么类,这通常表示设计缺陷。看看你是否可以使用虚拟函数获得所需的行为。

You really shouldn't. If your program needs to know what class an object is, that usually indicates a design flaw. See if you can get the behavior you want using virtual functions. Also, more information about what you are trying to do would help.

我假设你有这样的情况:

I am assuming you have a situation like this:

class Base;
class A : public Base {...};
class B : public Base {...};

void foo(Base *p)
{
  if(/* p is A */) /* do X */
  else /* do Y */
}



如果这是你所拥有的,那么尝试这样做:

If this is what you have, then try to do something like this:

class Base
{
  virtual void bar() = 0;
};

class A : public Base
{
  void bar() {/* do X */}
};

class B : public Base
{
  void bar() {/* do Y */}
};

void foo(Base *p)
{
  p->bar();
}

修改继续这么多年,我以为我应该引用一些参考。如果你有一个指针或对一个基类的引用,你的代码需要知道对象的派生类,那么它违反 Liskov替代原则叔叔叔叔将此称为 anathema to Object Oriented Design

Since the debate about this answer still goes on after so many years, I thought I should throw in some references. If you have a pointer or reference to a base class, and your code needs to know the derived class of the object, then it violates Liskov substitution principle. Uncle Bob calls this an "anathema to Object Oriented Design".

这篇关于如何检查对象的类型是否是C ++中的特定子类?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆