C++ - 尝试在类中使用全局时'Not a class or namespace'

C++ - 'Not a class or namespace' when try to use global in class

本文关键字:Not namespace or class 全局 C++      更新时间:2023-10-16

我有一个命名空间Global,在我的主函数之前有一个常量静态变量:

#include "RaGaCCMainView.h"
#include <QApplication>
namespace Global {
const static bool isLittleEndian = [](){
union {
uint32_t i;
char c[4];
} bint = {0x01020304};
return bint.c[0] == 1;
}();
}
int main(int argc, char *argv[])
{
QApplication a(argc, argv);
RaGaCCMainView w;
w.setAttribute(Qt::WA_QuitOnClose);
w.show();
return a.exec();
}

现在在RaGaCCMainView.h中,我想将变量声明为 extern:

extern const static bool Global::isLittleEndian;

这是我得到相应错误的地方:

C2653: 'Global': is not a class or namespace name

我只想在RaGaCCMainView.cpp中使用全局变量:

void RaGaCCMainView::someFunction()
{
...
if(Global::isLittleEndian) {
...
}
}

这似乎是一个愚蠢的问题,但我唯一能回答的答案没有帮助或不起作用。我(显然(想声明和定义一次Global::isLittleEndian,然后在这种情况下在我想要的任何类中使用它RaGaCCMainView.

如何使RaGaCCMainView知道Global::isLittleEndian存在以及它有什么价值?

我创建了一个定义预处理器宏IS_LITTLE_ENDIANEndianness.h文件:

#ifndef ENDIANNESS_H
#define ENDIANNESS_H
#include <QtGlobal>
#if Q_BYTE_ORDER == Q_LITTLE_ENDIAN
#define IS_LITTLE_ENDIAN 1
#else
#define IS_LITTLE_ENDIAN 0
#endif
#endif // ENDIANNESS_H

我将这个包含在类RaGaCCMainView中并使用宏IS_LITTLE_ENDIAN.