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
};
现在,对于这个基类的任何派生的
类,我希望使用相同的IDbase\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
,对吗?