C++运行时选择变量类型
C++ Variable Type Selection at Runtime
>我正在升级一个为特定硬件接口编写的旧应用程序。 我现在需要向现有应用程序添加对现代硬件的支持。
为此,我想为每个硬件类型创建一个类,并在用户选择其系统中的硬件时将变量分配给一种类型或另一种类型。
例如:
类 HardwareType1
和类 HardwareType2
都存在具有相同的成员函数。
object HW;
if (userHwType = 1)
// initialize HW as a HardwareType1 class
}
else{
// initialize HW as a HardwareType2 class
}
现在,我可以在整个代码中使用HW.doSomething()
,而无需在每次与硬件交互时对硬件类型设置条件。
敢肯定这是非常基本的,但老实说,我什至不知道这叫什么或搜索什么术语。
谢谢!
创建一个抽象基类,并从中派生两个具体的类:一个实现 type1,另一个实现 type2:
class Hardware
{
public:
virtual ~Hardware() {};
virtual void doSomething() = 0;
};
class Hardware1: public Hardware
{
public:
void doSomething() { // hardware type1 stuff. }
};
class Hardware2: public Hardware
{
public:
void doSomething() { // hardware type2 stuff. }
};
然后创建必要的实例:
std::unique_ptr<Hardware> hardware(1 == userHwType ? new Hardware1() :
new Hardware2());
hardware->doSomething();
如果您的编译器不支持 C++11,则std::unique_ptr
将不可用。替代智能指针将boost::scoped_ptr
(或boost::shared_ptr
)。
将多态性与一个常见的抽象基类一起使用,如下所示:
class HardwareBase
{
public:
virtual void Open() = 0;
virtual void Close() = 0;
virtual ~HardwareBase() {};
};
然后派生具体的硬件类型:
class HardwareType1 : public HardwareBase
{
public:
virtual void Open() {...}
virtual void Close() {...}
};
并选择所需的硬件实例:
std::unique_ptr<HardwareBase> hw;
if (userHwType == 1)
hw.reset(new HardwareType1());
else
hw.reset(new HardwareType2());
// And use it like this:
hw->Open();
请注意,您现在需要一个指向所选对象实例的指针。使用unique_ptr在退出时自动将其删除。
要搜索的术语是多态性;这是通过通用接口与不同类型的交互的一般术语。
在C++中,如果需要在运行时选择行为,通常的方法是定义一个抽象接口,该接口使用虚函数充当具体类型的基类 - 要调用的函数在运行时根据对象的真实类型选择。
// Abstract interface
class Hardware {
public:
virtual ~Hardware() {} // needed to safely delete objects
virtual void doSomething() = 0; // must be implemented by each concrete type
};
// One concrete type
class HardwareType1 : public Hardware
{
HardwareType1() { /* initialise */ }
void doSomething() { /* implementation for this type of hardware */ }
};
// Another concrete type
class HardwareType2 : public Hardware
{
HardwareType2() { /* initialise */ }
void doSomething() { /* implementation for this type of hardware */ }
};
现在,您可以选择要创建的内容,然后使用抽象接口进行交互:
// Create the correct type, depending on user input
std::unique_ptr<Hardware> hw
((userHwType == 1) ? new HardwareType1 : new HardwareType2);
// Do the right thing depending on the type
hw->doSomething();
您可以搜索工厂方法。这是您尝试实现的模式的名称
相关文章:
- 从模板创建通用打印函数,以打印基元数据类型变量的值
- 指针数据类型变量如何包含对象?
- 将 static_cast<int>(-15) 分配给静态常量字符类型变量
- 将内置类型变量传递给只有一个类类型参数的"+"运算符函数时自动类型转换的构造函数
- 如何为结构类型变量赋值
- 如何将字符类型变量附加到字符串中?
- 共享或私有 openmp 代码中的结构化类型变量
- 有没有办法在 c++ 中制作类型变量?
- 从其他类声明类类型变量会给出 C2143 错误(在"*"之前缺少";")
- 如何检查类中定义的枚举类型变量是否被分配给?
- 将子类实例保存在父类型变量中并通过父变量使用 Child 函数?
- 是否可以在没有结构的情况下创建新的类型变量?
- 为什么类型变量;不调用默认 CTR
- 如何使用CIN将输入整数值获取到char类型变量中
- 如何为 char** 类型变量提供适当的值,以便将其分配给字符串变量
- 在C++标准中哪里说必须初始化 const 内置类型变量的定义
- 为什么可以将其他类型变量用作C 中常量参考参数参数的参数
- Eclipse CDT 打开声明的自动类型变量
- 如何计算长长类型变量中的位数
- 将自动类型变量初始化为零.这种类型安全吗?