假设我有 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/