【问题标题】:C++ Namespace ofstream Won't Write流的 C++ 命名空间不会写入
【发布时间】: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 &lt;&lt; ... 行正常工作,而Constant::outsream &lt;&lt; ... 行没有做任何事情,即使我将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


【解决方案1】:

Constant::outstream 具有内部链接,因此为每个翻译单元创建一个单独的实例。总之,test.cpp 和 main.cpp 中的Constant::outstream 是两个不同的变量。

§3.5.2 具有命名空间范围 (3.3.6) 的名称如果是 — 显式声明为静态的变量、函数或函数模板;或者,

另一方面,静态类成员在整个程序中都是可见的。 所以,如果你会写

struct Constant
{
    static ofstream outstream;
}

而不是

namespace Constant
{
    static ofstream outstream;
}

它会起作用的。

但是,注意类必须有外部链接;例如你不应该放在匿名命名空间中。

【讨论】:

    猜你喜欢
    • 2016-05-20
    • 2014-04-16
    • 1970-01-01
    • 2010-12-23
    • 1970-01-01
    • 1970-01-01
    • 2020-01-23
    • 2014-09-02
    • 1970-01-01
    相关资源
    最近更新 更多