gpt4 book ai didi

c++ - 为什么 dynamic_cast 在这里给 nullptr 私有(private)继承?

转载 作者:行者123 更新时间:2023-11-30 02:44:06 27 4
gpt4 key购买 nike

谁能给我解释一下:

struct A {
virtual ~A() = default;
};

struct B : private A {
void foo() {
B* b = new B;
std::list<A*> list = {b};
B* back = dynamic_cast<B*>(list.back());
std::cout << back << std::endl;
}
};

int main() {
B b;
b.foo(); // nullptr
}

据我了解,只有 B 知道 B 派生自 A。foo() 是 B 的成员函数。因此从 A* 到 B* 的动态转换在 B::foo() 中应该没问题。那么为什么结果是nullptr呢?如果它是 protected 继承,情况也是一样。把inheritance改成public,一切就好了。这是怎么回事?

最佳答案

方式dynamic_cast<T>(v)执行其运行时检查在 §5.2.7 [expr.dynamic.cast]/p8 中指定:

If C is the class type to which T points or refers, the run-time check logically executes as follows:

  • If, in the most derived object pointed (referred) to by v, v points (refers) to a public base class subobject of a C object, and if only one object of type C is derived from the subobject pointed (referred) to o by v the result points (refers) to that C object.
  • Otherwise, if v points (refers) to a public base class subobject of the most derived object, and the type of the most derived object has a base class, of type C, that is unambiguous and public, the result points (refers) to the C subobject of the most derived object.
  • Otherwise, the run-time check fails.

请注意,检查仅对公共(public)基地成功。

关于c++ - 为什么 dynamic_cast 在这里给 nullptr 私有(private)继承?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25589158/

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