简体   繁体   English

C ++多态性,不完整的向下转换

[英]C++ Polymorphism, incomplete downcasting

I have an array which holds references to a bland base type, let's call it Object . 我有一个数组,其中包含对平淡基本类型的引用,我们称其为Object

I have derived Class1 from Object and Class2 from Class1 . 我从Object派生了Class1 ,从Class1派生了Class2

#include <vector>

class Object {};
class Class1 : public Object {
public:
virtual std::string ToString() {return "it is 1";}
};
class Class2 : public Class1 {
public:
    virtual std::string ToString() {return "it is 2";}
};

int _tmain(int argc, _TCHAR* argv[])
{
    std::vector<Object *> myvec;
    myvec.push_back(new Class2());
    printf("%s", (static_cast<Class1*>(myvec[0]))->ToString().c_str());
    return 0;
}

I call ToString() by casting from Object * to Class1 * like so 我通过将Object *Class1 *来调用ToString()

    printf("%s", (static_cast<Class1*>(myvec[0]))->ToString().c_str());

My question is, will this output 1 or 2 when the object is in fact of Class2 but not down cast to that specifically? 我的问题是,当对象实际上是Class2而不是具体转换为Class2时,输出1还是2? Is the virtual keyword having the intended effect? virtual关键字是否具有预期的效果?

It should call Class2 's virtual function, since the object is of that type. 它应该调用Class2的虚函数,因为该对象是该类型的。

Remember: the purpose of a virtual function is to call the actual class's function, not the function for the class the pointer/reference currently appears to be. 请记住:虚函数的目的是调用实际类的函数,而不是指针/引用当前似乎是的类的函数。

I slightly misread your question when I first answered, regarding demons and your nostrils. 初次回答时,我对您的问题有少许误解,涉及到恶魔和您的鼻孔。

The virtual keyword will have it's intended effect. virtual关键字将具有预期的效果。 That is, You will see 2. Although you have casted to Class1 , the vtable will work it's magic. 也就是说,您将看到2。尽管您已强制转换为Class1 ,但vtable可以正常运行。

First, this is not a safe cast. 首先,这不是一个安全的方法。 But assuming that myvec[i] is a pointer the an object you are casting to, then it will call the appropriate method for that class. 但是假设myvec[i]是您要投射到的对象的指针,则它将为该类调用适当的方法。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM