Warning: file_get_contents(/data/phpspider/zhask/data//catemap/6/cplusplus/140.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C++ 基类中的常量变量_C++_Abstract Class_Derived Class - Fatal编程技术网

C++ 基类中的常量变量

C++ 基类中的常量变量,c++,abstract-class,derived-class,C++,Abstract Class,Derived Class,我有两个类,Abstract和BaseAbstract是base类的基础 class Abstract { public: virtual ~Abstract(); const int aID; protected: // Constructor is protected because this class is abstract. Abstract(int xID) : aID(xID){} }; #def

我有两个类,
Abstract
Base
Abstract
base
类的基础

class Abstract 
{
public:
    virtual ~Abstract();

    const int                   aID;

protected:
    // Constructor is protected because this class is abstract.
    Abstract(int xID) : 
    aID(xID){}
};

#define BASE_CLASS_ID           0x0001

class Base : public Abstract
{
public:
    Base() : 
    Abstract(BASE_CLASS_ID){} // change the ID
};
现在,对于这个基类的任何
派生的
类,我希望使用相同的ID
base\u class\u ID

如何要求所有派生类采用此行为?

如果希望所有派生类都具有相同的常量数据成员辅助值,为什么不将此数据成员定义为静态常量数据成员?比如说

class Abstract 
{
public:
    virtual ~Abstract();
    enum  { BASE_CLASS_ID = 0x0001 };
    const static int aID = BASE_CLASS_ID;

protected:
    // Constructor is protected because this class is abstract.
    Abstract() = default;
};

你已经做到了!顺便说一句,派生函数将调用Base::Base(),但不是Abstract::Abstract()。您能解释一下如何调用吗?但是我不认为派生函数会自动调用基构造函数,或者会这样做?任何继承
Base
的类都必须调用
Base
的构造函数(在这种情况下不需要,因为
Base::Base()
没有参数,因此会自动调用它。
Base
的构造函数已经使用
Base\u CLASS\u ID
调用了
Abstract
的构造函数。我假设您声明的是
类派生:public Base
,对吗?