我如何在头文件中定义一个整数,以便每个包含头文件的 cpp 文件都具有 static const int id=0
,同时让 cpps 能够用其他值重新定义它。
我尝试使用弱符号但无法使其工作。
最佳答案
如果您对预处理器定义没问题,您可以这样做:
// header.h
#ifndef CLASSID
#define CLASSID 0
#endif
static int id=CLASSID;
// class.cpp
#define CLASSID 1
#include "header.h"
这样源文件可能会覆盖默认值,但也可能会忽略它,这是您提到的那种弱方法。
关于c++ - 使用默认值在 header 中定义静态整数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45783600/