5

如果我理解正确, typeid 可以确定多态中的实际类型,而 typeof 不能。

它们的返回是否也有不同的用途:typeof的返回用作类型关键字,可以定义变量,而typeid的返回不能?

有什么办法既可以获取多态的实际类型,又可以使用 return 作为类型关键字来定义另一个变量?我希望从指向基类的指针中获取派生类类型,并定义派生类的变量或指向派生类的指针。就像是:

baseclass *p = new derivedclass  
typexxx(*p) *pp = dynamic_cast<typexxx(*p) *> (p); 
// would like to convert the pointer from pointing to a base class 
// to its derived class

非常感谢你!

4

2 回答 2

7

c++0x将具有decltype可以像这样使用的:

int someInt;
decltype(someInt) otherIntegerVariable = 5;

但是对于普通的旧 c++,不幸的是,没有。

我想这decltype也不会有太大帮助,因为你想要多态类型,而不是声明的类型。做你想做的最直接的方法是尝试动态转换为特定类型并检查NULL.

struct A {
    virtual ~A() {}
};
struct B : public A {};
struct C : public A {};

int main() {
    A* x = new C;
    if(B* b_ptr = dynamic_cast<B*>(x)) {
        // it's a B
    } else if(C* c_ptr = dynamic_cast<C*>(x)) {
        // it's a C
    }
}
于 2009-12-31T22:07:13.797 回答
3

假设层次结构 A <- B <- C

A * p = new AorBorC;   // create new object of some sort

if ( dynamic_cast <C*>(p) ) {
  C * c = dynamic_cast <C*>(p);
  c->CFunc();
}
else if ( dynamic_cast <B*>(p) ) {
  B * b = dynamic_cast <B*>(p);
  b->BFunc();
}
else if ( dynamic_cast <A*>(p) ) {
  A * a = dynamic_cast <A*>(p);
  a->AFunc();
}

其中 AFunc、BFunc、CFunc 特定于它们各自的类,而不是虚拟的。显然,这可以进行一些优化。

于 2009-12-31T22:44:13.453 回答