在基类的对象上调用派生类的方法

发布于 2024-10-10 16:16:45 字数 343 浏览 3 评论 0原文

我写了几行我认为不应该编译的代码。我在指向基类对象的 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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

平生欢 2024-10-17 16:16:45

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 use static_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 used static_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.

眼泪淡了忧伤 2024-10-17 16:16:45

使用 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."

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文