在基类的对象上调用派生类的方法
我写了几行我认为不应该编译的代码。我在指向基类对象的 static_cast-ed 指针上调用派生类的方法,如下所示:
class B {};
class D: public B
{
public:
void bar() { printf("%d\n", m_i); }
private:
int m_i;
};
int main()
{
B b;
D* d = static_cast<D*>(&b);
d->bar();
return 0;
}
打印的值显然是垃圾,但这是否应该编译? gcc 是如何做到这一点的?
I have written a few lines of code which I think should not compile. I am calling a method of a derived class on a static_cast-ed pointer to object of base class as follows:
class B {};
class D: public B
{
public:
void bar() { printf("%d\n", m_i); }
private:
int m_i;
};
int main()
{
B b;
D* d = static_cast<D*>(&b);
d->bar();
return 0;
}
The value printed is obviously junk but should this even compile? How does gcc
manage to do that?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
gcc
不能保证它是不正确的,除非在少数情况下它确实不值得检查。当你使用static_cast
时,你就向编译器保证你知道你在做什么。这里有两种类型的演员。
static_cast
,也就是说,您告诉编译器指向基类的指针是指向派生类的指针,然后闭嘴并继续处理它。dynamic_cast
,也就是说,您要求编译器检查指向基的指针是否确实是指向派生的指针。您使用了static_cast
,因此编译器关闭并按照您所说的进行操作。编辑:John 准确地指出,您的继承层次结构中没有虚函数,因此您应该从 C++ 中解雇,并且
dynamic_cast
仅对虚函数有效。gcc
can't guarantee that it's incorrect, except in enough of a minority of cases that it really isn't worth checking. When you usestatic_cast
, then you are promising the compiler that you know wtf you're doing.There are two kinds of casts here.
static_cast
, which is, you are telling the compiler that pointer to a base IS a pointer to derived, and shut up and get on with it.dynamic_cast
, which is, you are asking the compiler to check if that pointer to base is indeed a pointer to derived. You usedstatic_cast
, so the compiler shut up and did as you said.Edit: John accurately pointed out that there are no virtual functions in your inheritance hierarchy, for which you should be fired from C++, and
dynamic_cast
is only valid for virtual functions.使用 static_cast<>你告诉编译器“我知道我在做什么,B*实际上是D*,闭嘴,照我说的做。”
Using the static_cast<> you told the compiler "I know what I am doing, that B* is actually D*, shut up and just do what I say."