c++ - dynamic_cast的继承与使用

标签 c++ inheritance oop dynamic-cast

假设我有 3 个类如下(因为这是一个例子,它不会编译!):

class Base
{
public:
   Base(){}
   virtual ~Base(){}
   virtual void DoSomething() = 0;
   virtual void DoSomethingElse() = 0;
};

class Derived1
{
public:
   Derived1(){}
   virtual ~Derived1(){}
   virtual void DoSomething(){ ... }
   virtual void DoSomethingElse(){ ... }
   virtual void SpecialD1DoSomething{ ... }
};

class Derived2
{
public:
   Derived2(){}
   virtual ~Derived2(){}
   virtual void DoSomething(){ ... }
   virtual void DoSomethingElse(){ ... }
   virtual void SpecialD2DoSomething{ ... }
};

我想根据某些直到运行时才可用的设置创建 Derived1 或 Derived2 的实例。

因为直到运行时我才能确定派生类型,那么您认为以下是不好的做法吗?...

class X
{
public:
   ....

   void GetConfigurationValue()
   {
      ....
      // Get configuration setting, I need a "Derived1"
      b = new Derived1();

      // Now I want to call the special DoSomething for Derived1
      (dynamic_cast<Derived1*>(b))->SpecialD1DoSomething();      
   }
private:
   Base* b;
};

我通常读到 dynamic_cast 的用法不好,但正如我所说,我不知道 在运行时创建哪种类型。请帮忙!

最佳答案

为什么不通过将指向派生的指针分配给指向基的指针来延迟“丢弃”一些 if 类型信息的时刻:

void GetConfigurationValue()
{
  // ...
  // Get configuration setting, I need a "Derived1"
  Derived1* d1 = new Derived1();
  b = d1;

  // Now I want to call the special DoSomething for Derived1
  d1->SpecialD1DoSomething();
}

关于c++ - dynamic_cast的继承与使用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3065200/

相关文章:

c++ - 从函数获取 char* 后的条件 gdb 断点

c++ - 如何找出变量的类型,涉及继承/多态性

javascript - JavaScript 中构造函数指针行为背后的基本原理是什么?

java - java中泛型方法的区别

c++ - 将 std::strings 插入到 std::map

c++ - 保持 shared_ptr use_count() 为 1

python - 避免创建新的方法对象

C++从已经初始化的父类创建子类

python - 特殊的 __init__() 方法

c++ - 您是否应该使用显式类型转换更正有关类型转换的编译器警告?