gpt4 book ai didi

c++ - 动态转换后未发现不良转换

转载 作者:塔克拉玛干 更新时间:2023-11-03 01:18:45 25 4
gpt4 key购买 nike

我怎么可能用非 const Triangle 指针成功通过 try?

const Triangle *prim;
const GeometricPrimitive *gp;
try {
gp = dynamic_cast<const GeometricPrimitive*>(primitives[edges[axis][j].primNum].GetPtr());
prim = dynamic_cast<const Triangle*>((gp->shape).GetPtr());
}
catch (std::bad_cast& bc) {
continue;
}

enter image description here

template <typename T> class Reference {
public:
...
T *operator->() { return ptr; }
const T *operator->() const { return ptr; }
operator bool() const { return ptr != NULL; }
const T *GetPtr() const { return ptr; }
private:
T *ptr;
};

编辑: enter image description here

最佳答案

dynamic_cast 的语义在 §5.2.7/8 中描述:

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 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.

第 9 段:

The value of a failed cast to pointer type is the null pointer value of the required result type. A failed cast to reference type throws std::bad_cast (18.7.2).

注意:您可能应该包括 <typeinfo>对于 std::badcast .

关于c++ - 动态转换后未发现不良转换,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27214556/

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