C++ 多态:从父类到子类 [英] C++ Polymorphism: from parent class to child

查看:264
本文介绍了C++ 多态:从父类到子类的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在C++中,我们可以将子类指针转换为父类,但有什么方法可以将其转换回来:从父类,从子类中获得,返回子类?

In C++ we can convert child class pointer to parent, but is there any way to convert it back: from parent, which was obtained from child, give child class back?

我的意思是:

class Parent
{
    ...
};

class Child : public Parent
{
    ...
};

int main(int argc, char const *argv[])
{
    Child* child = new Child();
    Parent* parent = child;
    Child* old_child = parent; // how to do this??
    return 0;
}

感谢您的回答.

推荐答案

但是有什么办法可以将它转换回来:从父级,从子级获得,还给子级?"

是的,正如其他答案中提到的,有两种方法可以做到这一点.

Yes, as mentioned in the other answers, there are two ways to do this.

Child * old_child = dynamic_cast<Child*>(parent);

dynamic_cast<> 的结果 可以在运行时检查,从而可以确定 parent 对象是否真的代表一个 Child 实例:

The result of the dynamic_cast<> can be checked at runtime, thus you can determine if the parent object really represents a Child instance:

if(!old_child) {
     // parent is not a Child instance
}

另请注意,要使其正常工作,有问题的类需要有一个 vtable,RTTI 可以实际确定它们的关系.实现此目的的最简单形式是为 Parent 类提供一个虚拟析构函数

Also note to get this working properly, the classes in question need to have a vtable, that RTTI can actually determine their relation. The simplest form to achieve this, is giving the Parent class a virtual destructor function

class Parent {
public:
    virtual ~Parent() {}
    // or
    // virtual ~Parent() = default;
    // as suggested for latest standards
};

注意:
如果这适用于一般设计决策,我会强烈忽略它.改用纯虚拟接口,保证执行或不执行.

NOTE:
If this should apply to a general design decision, I would strongly disregard it. Use pure virtual interfaces instead, that are guaranteed to be implemented, or not.

第二种方式static_cast<> 可以用在你很清楚parent 实际上是一个孩子的环境中.最简单的形式是 CRTP,其中 Parent 将继承类作为模板参数

The second way of static_cast<> can be used in environments, where you well know that parent actually is a child. The simplest form of this is the CRTP, where Parent takes the inheriting class as a template parameter

template <class Derived>
class Parent {

     void someFunc() {
         static_cast<Derived*>(this)->doSomething();
     }
};

class Child : public Parent<Child> {
public:
    void doSomething();
};

将在编译时检查 Parent<>static_cast<> 实例化的有效性.

The validity of an instatiation of Parent<> and static_cast<> will be checked at compile time.

注意:
另一个优点是您可以使用派生接口来使用

NOTE:
Another advantage is that you can use an interface for derived that makes use of

  • Derived 的静态类成员
  • typedefDerived
  • 提供
  • ...更多类特性,可以在编译时检查

这篇关于C++ 多态:从父类到子类的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆