开发者

Seeing what class an object is

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


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
}


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜