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)
相关问题
- Sorting 3 numbers without branching [closed]
- How to compile C++ code in GDB?
- Why does const allow implicit conversion of refere
- thread_local variables initialization
- What uses more memory in c++? An 2 ints or 2 funct
相关文章
- Class layout in C++: Why are members sometimes ord
- How to mock methods return object with deleted cop
- Which is the best way to multiply a large and spar
- C++ default constructor does not initialize pointe
- Selecting only the first few characters in a strin
- What exactly do pointers store? (C++)
- Converting glm::lookat matrix to quaternion and ba
- What is the correct way to declare and use a FILE
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:
If this is what you have, then try to do something like this:
Edit: 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".
In c# you can simply say:
You can do it with
dynamic_cast
(at least for polymorphic types).Actually, on second thought--you can't tell if it is SPECIFICALLY a particular type with
dynamic_cast
--but you can tell if it is that type or any subclass thereof.Well, yes, it could be done by comparing:
typeid().name()
. If we take the already described situation, where:A possible implementation of
foo(Base *p)
would be: