我的代码示例很简单:
#include <fstream>
int main() {
int printDebug=1; // 1 - turn on, 0 -turn off.
if (printDebug==1){
ofstream output_file("outputDelta.txt"); // create output file
}
for (int i = 0; i < 1e2; i++){
if (printDebug==1){
output_file << i <<"\n";
}
}
return 0;
}
它不编译,因为“错误:‘output_file’未在此范围内声明”。 如果我不在 printDebug 模式下,我的整个想法是不要声明任何 output_file。我不想创建空输出或分配内存。你会如何解决它?
您需要知道作用域在 C++ 中是如何工作的。如果你在一个范围内有一个变量(在
{ }
之间),这个变量将在其范围结束时被销毁。
void main()
{ // scope of function main()
int x;
{ // new scope
int y;
} // y gets destroyed here
} // x gets destroyed here
if
语句的主体也是一个作用域。即使你没有大括号,只有这样一个语句:
if (true) // new scope
int z;
// end of this scope
变量只能在其声明的范围内或任何嵌套范围内使用。这意味着我仍然可以在声明
x
的新范围内使用第一个代码片段中的 y
,但我无法从外部范围访问 y
。
当我理解你的意图正确时,你想要类似这样的东西:
#include <fstream>
#define DEBUG_LEVEL 1
int main() {
#if DEBUG_LEVEL == 1
std::ofstream output_file("outputDelta.txt"); // create output file
#endif
for (int i = 0; i < 1e2; i++) {
#if DEBUG_LEVEL == 1
output_file << i << "\n";
#endif
}
return 0;
}
请注意,
DEBUG_LEVEL
现在不是变量而是宏。预处理器将检查您的 #if
s 的条件,如果它们的计算结果为真,则将代码保留在两者之间,否则将其删除。因此,所有“删除”的代码都不会被编译。
当您将 DEBUG_LEVEL
设置为其他内容时,就好像您刚刚注释掉了每个 #if DEBUG_LEVEL == 1
和 #endif
之间的行。