【发布时间】:2014-04-20 05:08:33
【问题描述】:
我正在用 C++ 制作游戏。我已经声明了一个常量命名空间,用于我需要在整个程序中访问的全局值。在那里我有一个用于调试目的的 ofstream(是的,我知道它不是“恒定的”,但它最适合那里),它只在感觉像它时输出。我能够制作一个小程序来演示这个问题。我为它分散在 4 个文件中而道歉,但我保证这很重要。
main.cpp:
// Include necessary files
#include "test.h"
#include "constants.h"
#include <fstream>
using namespace std;
int main(int argc, char* argv[])
{
// Start of program
Constant::outstream.open("test.txt");
// ...
// Do stuff
// Output debugging info
Test test;
test.print("Test", Constant::outstream);
// ...
// Do other stuff
// End of program
Constant::outstream.close();
return 0;
}
常量.h:
#ifndef _CONSTANTS_H
#define _CONSTANTS_H
#include <fstream>
namespace Constant
{
static ofstream outstream;
}
#endif
test.h:
#ifndef _TEST_H
#define _TEST_H
#include <string>
#include <fstream>
#include "constants.h"
class Test
{
public:
void print(string str, ofstream& out);
};
#endif
test.cpp:
#include "test.h"
using namespace std;
void Test::print(string str, ofstream& out)
{
out << "out: " << str << endl << flush; // Works
Constant::outstream << "Constant::outstream: " << str << endl << flush; // Doesn't
}
在 test.cpp 文件中,out << ... 行正常工作,而Constant::outsream << ... 行没有做任何事情,即使我将Constant::outstream 作为out 参数传递!我看不出这两行有什么不同的原因。
在发布之前,我尝试将 test.cpp 的代码放在 test.h 中,只是为了减少问题的文件,并且很惊讶地看到它可以工作。如果我将Test::print() 函数复制粘贴到test.h 中(无论是在class Test { ... } 内部还是外部),那么两个输出命令都可以正常工作。仅当Test::print() 的实现位于单独的文件中时才会出现此问题。
似乎对Constant::outstream 的任何引用都不能在类 cpp 文件中工作(没有编译错误,只是没有任何反应)。它适用于 main.cpp 和类头文件,但似乎不适用于任何类 cpp 文件。不幸的是,这是一个我正在编写的大程序,几乎每个类都有自己的 cpp 实现文件,而这确实是我需要使用这个 ofstream 的一个地方。有人知道这是什么原因吗?
提前致谢,
道格
【问题讨论】:
-
简短回答,不要在头文件中定义变量。每个包含该文件的 cpp 都有一个不同的变量。
-
您是否尝试过将
static ofstream outstream;更改为extern ofstream outstream;,然后在您的主文件中声明它(无论是main.cpp 还是test.cpp).. ?? -
@txtechhelp: 将
static更改为extern会给我一个“未解析的外部符号”错误。 “在主文件中声明它”到底是什么意思。 in 不是已经在 constants.h 中声明了吗? -
查看@RetiredNinja 发布的答案;您只在
constants.h文件中定义了它,现在必须在 main.cpp 或 test.cpp 文件中声明它,方法是将ofstream Constant::outstream;放在文件的某个位置(通常在您的#include语句之后)
标签: c++ namespaces fstream