Seeing what class an object is

主宰稳场 提交于 2020-01-06 13:12:09

问题


If I have a pointer to a base class A in C++, how would I be able to tell in my code that the pointer is to a derived class B or C?


回答1:


Assuming the base class A is polymorphic (i.e. it has at least one virtual function), you can use dynamic_cast. Given an A* ap;:

if (B* bp = dynamic_cast<B*>(ap)) {
    // the object is a B
}
else if (C* cp = dynamic_cast<C*>(ap)) {
    // the object is a C
}



回答2:


You generally shouldn't need to know:

struct A {
    virtual int generate_foo() = 0;
};

struct B : A {
    int generate_foo() { return 42; }
};

struct C : A {
    i_;
    C(int i) : i_(i) { }
    int generate_foo() { return i_++; }
};

If you have an A* you (1) know that it has a generate_foo() method, and (2) know that generate_foo() will generate an appropriate foo for whatever object you really do have. In general that should be enough and you should be able to keep track of when you have an A*.

Philosophically, the designers of C++ spent years trying to avoid adding runtime type information because it' too easily used incorrectly. However, they eventually decided that they were on the wrong end of a losing battle and added dynamic_cast and typeinfo(). C++0x will add more.




回答3:


Another approach,

if ( typeid(*pBase) == typeid(A))
{
      cout << "A" << endl;
}
else if ( typeid(*pBase) == typeid(B))
{
      cout << "B" << endl;
}
else if ( typeid(*pBase) == typeid(C))
{
      cout << "C" << endl;
}
else
{
      cout << "something else" <<endl;
}

But I would prefer James's approach, because using that you don't only determine the type, but you also have the type-casted instance to work with, afterwards!



来源:https://stackoverflow.com/questions/4426476/seeing-what-class-an-object-is

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!