在派生成员变量上调用虚拟功能
这个小测试程序崩溃了,我很感兴趣为什么这样做:
#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 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
基类和成员按类中的声明顺序初始化,而不是按照您在初始化列表中的顺序进行初始化。
碱总是在成员面前初始化的基础,因此基地的构造函数将指向非初始化对象的指针,即未定义的行为。
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.