将基对象返回到向上转换的派生类的最合适方法是什么?
struct B {}; // B contains data members
struct D : B {}; // D doesn't contain ANY data member
B g_b; // global object
D& fun () // want to return by reference ONLY
{
return <???>(g_b); // how ???
}
[注意:我想避免重载构造函数(或赋值),例如 D(const B&)
。]
struct B {}; // B contains data members
struct D : B {}; // D doesn't contain ANY data member
B g_b; // global object
D& fun () // want to return by reference ONLY
{
return <???>(g_b); // how ???
}
[Note: I want to avoid overloading constructor (or assignment) such as D(const B&)
.]
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
你试图做的事情是非法的。
g_b
不是D
。What you're trying to do is illegal.
g_b
is not aD
.没有合适的演员。这实际上是未定义的行为。
有关详细信息,请参阅此主题:向下转型基本类型
注意:术语是向下转型 当你将基类转换为派生类时;当将派生类强制转换为基类时,将使用术语向上转换。
No suitable cast. That is in fact undefined behavior.
For detail, see this topic: Downcasting a base type
Note : the term is downcast when you cast base to derived class; and the term upcast is used when you cast derived to base class.
这是未定义的行为。
您可以使用
dynamic_cast
执行基类指针/引用到派生类指针/引用的安全向下转换。如果是指针,则返回 null;如果是引用,则抛出异常。That is undefined behavior.
You can use
dynamic_cast
for performing safe down casting of Base class pointer/reference to derived class pointer/reference. It returns a null in case of pointers or throws an exception in case of references.