我想创建一个类,这些类是从使用程序的某个特征时派生出来的,只需要初始化一次。
我使用静态bool成员和默认构造函数创建了类。默认构造函数检查静态成员并在需要时运行初始化:
class WireUser {
public:
static bool wireIntialized;
WireUser::WireUser();
};
bool WireUser::wireInitialized = false;
WireUser::WireUser() {
if (!wireInitialized) {
Wire.begin();
wireInitialized = true;
}
};
当我尝试编译时,我收到以下错误:
error: 'bool WireUser::wireInitialized' is not a static member of 'class WireUser' bool WireUser::wireInitialized = false;
如果删除该行,则该成员初始化为false,包含if (!wireInitialized) {
的行上会出现相同的错误
我不明白我做错了什么。
答案 0 :(得分:4)
您的代码中存在许多拼写错误和小错误/警告(注释中说明的修复步骤):
class WireUser {
public:
static bool wireInitialized;
WireUser(); // Don't use scope specifiers in declarations: WireUser::WireUser();
};
bool WireUser::wireInitialized = false; // Typo fixed here 'wireInitialized' isn't the
// same as 'wireIntialized'
WireUser::WireUser() {
if (!wireInitialized) {
// Wire.begin(); Commented out because it's not in context of your question
wireInitialized = true;
}
} //; <<<< Omit the semicolon to get rid of the warning
int main (){
WireUser wu;
return 0;
}
此外,您应该考虑使该线程安全地进行初始化
std::atomic<bool>
可能是正确的选择:
#include <atomic>
class WireUser {
public:
static std::atomic<bool> wireInitialized;
WireUser();
};
std::atomic<bool> WireUser::wireInitialized = {false};
WireUser::WireUser() {
if (!wireInitialized.exchange(true)) {
// Wire.begin();
// wireInitialized = true;
}
}
int main (){
WireUser wu;
return 0;
}