Typedef是一个具有特定构造函数参数的类

Typedef a class with specific constructor argument

本文关键字:构造函数 参数 一个 Typedef      更新时间:2023-10-16

让我们从C++中的一个简单类开始:

class aClass {
        bool b;
        aClass(bool x){b=x;} 
};

是否可以键入两个新类型stateTrue和stateFalse,这样如果我这样做:

stateTrue variable;

它将被翻译为:

aClass  variable(true); 

继承的替代方案可以是使aClass成为template:

template <bool T>
class aClass
{
public:
    bool b;
    aClass(): b(T) {}
};
typedef aClass<true>  stateTrue;
typedef aClass<false> stateFalse;
不,因为那是一个实例,而不是一个类型。

您可以导出:

class stateTrue: public aClass {
public:
    stateTrue() : aClass(true) {}
};

最接近的是

class stateTrue : // new type needed, not just a new name
  public aClass { // but obviously can be converted to aClass
  public: stateTrue() : aClass(true) { } // Default ctor sets aClass base to true
};