main.cpp
的很多地方都撒满了Log
:
#include "utils.hpp"
...//some code
int main(){
int a = 0;
int b = 0;
util::LogClass::Log("Initial","something);
//some more code
util::LogClass::Log("Mid","something");
//some more code
util::LogClass::Log("Middle","something");
}
并且LogClass在utils.hpp
中定义如下:
namespace util{
class LogClass{
public:static bool LOG_ENABLED;
public: static void Log(std::string tag, std::string message){
if(LOG_ENABLED){
std::cerr << tag+": "+message <<std::endl;}
}
}
bool LogClass::LOG_ENABLED=true;
}
我以为我可以在main.cpp
中做到这一点:
#include "utils.cpp"
util::LogClass::LOG_ENABLE=false;
int main(){ //the previous main function}
*上面的代码实际上给出了一个错误,说:bool util :: LogClass :: LOG_ENABLED的重新定义bool util :: LogClass :: LOG_ENABLE = false *
但是,如果我将其移动到主体内部:
#include "utils.cpp"
int main(){ util::LogClass::LOG_ENABLED=false; //the previous main function}
然后代码可以正常编译。所以我的问题是,即使它是静态成员,为什么也不能在main()
函数之外启用它,为什么[g++
)编译器会将其重新定义?
您只能在定义变量的位置静态初始化它。主函数内部的初始化是动态的,所以很好。
尽管我同意编译器错误很奇怪-编译器可能正在尝试自动扣除应该重新定义的“缺失”类型。