gpt4 book ai didi

c++ - 标准中关于 "virtual function call in base constructor"的部分在哪里

转载 作者:行者123 更新时间:2023-11-30 03:47:14 27 4
gpt4 key购买 nike

基类构造函数中的虚函数调用调用基类中的一个,而不是派生类中的一个。

iso-cpp 标准在哪个部分讨论了这个问题?

最佳答案

$12.7/4 构造和破坏 [class.cdtor](由我加粗)

Member functions, including virtual functions (10.3), can be called during construction or destruction (12.6.2). When a virtual function is called directly or indirectly from a constructor or from a destructor, including during the construction or destruction of the class’s non-static data members, and the object to which the call applies is the object (call it x) under construction or destruction, the function called is the final overrider in the constructor’s or destructor’s class and not one overriding it in a more-derived class. If the virtual function call uses an explicit class member access (5.2.5) and the object expression refers to the complete object of x or one of that object’s base class subobjects but not x or one of its base class subobjects, the behavior is undefined. [ Example:

struct V {
virtual void f();
virtual void g();
};
struct A : virtual V {
virtual void f();
};
struct B : virtual V {
virtual void g();
B(V*, A*);
};
struct D : A, B {
virtual void f();
virtual void g();
D() : B((A*)this, this) { }
};
B::B(V* v, A* a) {
f(); // calls V::f, not A::f
g(); // calls B::g, not D::g
v->g(); // v is base of B, the call is well-defined, calls B::g
a->f(); // undefined behavior, a’s type not a base of B
}

—end example ]

关于c++ - 标准中关于 "virtual function call in base constructor"的部分在哪里,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33749603/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com