在派生成员变量上调用虚拟功能

发布于 2025-01-18 11:40:04 字数 670 浏览 2 评论 0原文

这个小测试程序崩溃了,我很感兴趣为什么这样做:

#include <iostream>

struct SomeClass {
    SomeClass() {
    }
    
    virtual ~SomeClass() {
    }
    
    void test() {
        std::cout << "test" << std::endl;
    }
    
    virtual void onInit() {
        std::cout << "test" << std::endl;
    }
};

struct Base {
    Base(SomeClass *ptr) {
        ptr->test();
        ptr->onInit();
    }
};

struct Derived : Base {
    SomeClass cls;
    
    Derived() : cls(), Base(&cls) {
    }
};

int main(int, const char **) {
    Derived test;
}

为什么我不能从基类中调用虚拟函数 oninit ?当我在初始化器列表中使用cls()时,这不是完全初始化的吗?

This little test program crashes and I'm interested why it does:

#include <iostream>

struct SomeClass {
    SomeClass() {
    }
    
    virtual ~SomeClass() {
    }
    
    void test() {
        std::cout << "test" << std::endl;
    }
    
    virtual void onInit() {
        std::cout << "test" << std::endl;
    }
};

struct Base {
    Base(SomeClass *ptr) {
        ptr->test();
        ptr->onInit();
    }
};

struct Derived : Base {
    SomeClass cls;
    
    Derived() : cls(), Base(&cls) {
    }
};

int main(int, const char **) {
    Derived test;
}

Why can't I call the virtual function onInit from the base class? Isn't that fully initialized when I use cls() in the initializer list?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

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

发布评论

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

评论(1

不交电费瞎发啥光 2025-01-25 11:40:04

基类和成员按类中的声明顺序初始化,而不是按照您在初始化列表中的顺序进行初始化。

碱总是在成员面前初始化的基础,因此基地的构造函数将指向非初始化对象的指针,即未定义的行为。

Base classes and members are initialized in the order of declaration in the class and not in the order you put in the initialization list.

Bases are always initialized before members, so the Base's constructor dereferences a pointer to an uninitialized object, which is undefined behavior.

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