问题描述
这可能是一个非常简单的问题,但是我一直在寻找答案已有一段时间了,但似乎无法弄清楚.我正在尝试在类中初始化常量变量常量指针.这是头文件:
This is probably a ridiculously easy question, but I've been searching around for the answer for a while yet can't seem to figure this out. I'm trying to initialize a constant variable constant pointer in a class. Here is the header file:
class Scheduler{
public:
Scheduler();
explicit Scheduler( unsigned long * );
private:
const unsigned long *const thresh;
};
这是该类的构造函数
Scheduler::Scheduler( unsigned long * threshold ):
thresh(threshold)
{}
当我尝试编译此代码时,我遇到此错误:
When I attempt to compile this code I run into this error:
scheduler.cpp: In constructor ‘Scheduler::Scheduler()’:
scheduler.cpp:3: error: uninitialized member ‘Scheduler::thresh’ with ‘const’ type ‘const long unsigned int* const’
许多在线讨论成员变量构造函数中的常量成员变量的源均指向使用初始化程序列表.我想我正在做我应该做的事,但显然仍然不好.谁能看到什么问题?
Multiple sources online discussing constant member variables in constructors for member variables point to using initializer lists. I think I'm doing what I'm supposed to, but apparently it's still no good. Can anyone see what's wrong?
推荐答案
您必须在 ALL 构造函数的初始化列表中初始化常量成员.您仅对带有参数的对象执行此操作.也将它作为默认值,一切都会好起来的.在这种情况下,请使用0初始化阈值,或禁用默认构造函数.
You must initialize your constant member in the initialization list of ALL constructors. You are doing it only for the one with an argument. Do it for the default one too, and everything will be fne. In this particular case, either initialize your thresh with 0, or disable the default constructor.
这篇关于类中未初始化的常量成员的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!