How can I initialize a const variable of a base class in a derived class#39; constructor in C++?(如何在 C++ 中的派生类的构造函数中初始化基类的 const 变量?)
问题描述
I have an abstract C++ class with no constructor. It's supposed to be a base class so other classes can inherit from it. What I am trying to do is to declare a constant variable in the base class and initialize it in each derived class' constructor but nowhere else in each one of those classes. Is it legal in C++? If so, how can I do that?
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) { }
};
这篇关于如何在 C++ 中的派生类的构造函数中初始化基类的 const 变量?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:如何在 C++ 中的派生类的构造函数中初始化基类的 const 变量?


基础教程推荐
- CString 到 char* 2021-01-01
- 我应该对 C++ 中的成员变量和函数参数使用相同的名称吗? 2021-01-01
- 为什么 typeid.name() 使用 GCC 返回奇怪的字符以及如 2022-09-16
- 为什么 RegOpenKeyEx() 在 Vista 64 位上返回错误代码 2021-01-01
- GDB 显示调用堆栈上函数地址的当前编译二进制文 2022-09-05
- 如果我为无符号变量分配负值会发生什么? 2022-01-01
- 为什么派生模板类不能访问基模板类的标识符? 2021-01-01
- 通过引用传递 C++ 迭代器有什么问题? 2022-01-01
- 初始化列表*参数*评估顺序 2021-01-01
- 非静态 const 成员,不能使用默认赋值运算符 2022-10-09