C++多态、不完全向下转型
我有一个数组,其中包含对平淡基类型的引用,我们将其称为Object
。
我从 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;
}
我通过从 Object *
转换为 Class1 *
来调用 ToString()
printf("%s", (static_cast<Class1*>(myvec[0]))->ToString().c_str());
我的问题是,当对象为事实上是 Class2
但不是专门向下转换? virtual
关键字是否达到预期效果?
I have an array which holds references to a bland base type, let's call it Object
.
I have derived Class1
from Object
and Class2
from Class1
.
#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
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? Is the virtual
keyword having the intended effect?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
它应该调用 Class2 的虚函数,因为该对象属于该类型。
请记住:虚函数的目的是调用实际类的函数,而不是指针/引用当前显示的类的函数。
It should call
Class2
's virtual function, since the object is of that type.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.
当我第一次回答你的问题时,我有点误解了你的问题,关于恶魔和你的鼻孔。
virtual
关键字将达到预期的效果。也就是说,您将看到 2。尽管您已转换为Class1
,但 vtable 将发挥其魔力。I slightly misread your question when I first answered, regarding demons and your nostrils.
The
virtual
keyword will have it's intended effect. That is, You will see 2. Although you have casted toClass1
, the vtable will work it's magic.首先,这不是一个安全的转换。但假设 myvec[i] 是您要转换到的对象的指针,那么它将调用该类的适当方法。
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.