Is it legal in C++?
No. The constant must be initialized in the base class constructor.
The solution is to provide an appropriate constructor in your base class – otherwise it cannot be used. Furthermore, there’s no reason not to provide that constructor.
class Base {
int const constant;
public:
virtual ~Base() = 0; // Makes this an abstract base class.
protected:
Base(int c) : constant(c) { }
};
// Must be implemented!
Base::~Base() { }
class Derived : public Base {
public:
Derived() : Base(42) { }
};
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…