Mew*_*zer 0 c++ oop inheritance 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{ ... }
};
Run Code Online (Sandbox Code Playgroud)
我想创建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;
};
Run Code Online (Sandbox Code Playgroud)
我一般都认为dynamic_cast的用法很糟糕,但正如我所说,我不知道在运行时要创建哪种类型.请帮忙!
如果类型信息通过将指向派生的指针分配给指向base的指针,为什么不延迟你"抛弃"某些时刻:
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();
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
2324 次 |
| 最近记录: |