c++ - "Undefined reference"尝试引用静态字段

标签 c++ undefined-reference

我的测试类有这样的定义:

#ifndef TEST_H
#define TEST_H

#include <iostream>
#include <cstdlib>
#include <ctime>
#include <fstream>

class Test {
      public:
          static bool testAll(bool debug = false);           
      private:
          static bool testVector2D(bool debug = false);
          static bool testPolygon(bool debug = false);
          static bool testRectangle(bool debug = false);
          static bool testMap(bool debug = false);

          static std::ofstream outStream;
          static std::ifstream inStream;

          static void prepareWriting();
          static void prepareReading();

          const char tempFileName[];
};   

当我尝试使用 Test::outStream 或 Test::inStream 时,例如这里:

void Test::prepareWriting() {
    if (Test::inStream.is_open()) {
        Test::inStream.close();
    }
    Test::outStream.open(testFileName,ios::out); 
}

我收到此消息:“对`Test::inStream'的 undefined reference ”

我读过一些关于初始化 .cpp 文件中的静态成员的内容,但我不知道如何使用 fstream 来做到这一点

最佳答案

您需要定义流,在其中定义其他测试方法:

std::ofstream Test::outStream;
std::ifstream Test::inStream;

关于c++ - "Undefined reference"尝试引用静态字段,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9446365/

相关文章:

c - undefined reference ... - 链接问题?

c++ - 未定义对我的函数的引用

jquery - 仅在 Internet Explorer 中引发未定义或 null 引用的 datepicker 元素

c++ - 条件反序列化

c++如何在内部循环中使用带自动的 vector 删除对象

c++ - 在 C++ 中使用 istringstream 读取输入时出错

c++ - 什么是 undefined reference /未解析的外部符号错误,我该如何解决?

c++ - 在 Windows 中,有没有办法在新的 MIDI 端口可用时收到通知?

c++ - Intel Pin 获取函数参数号

c - 错误: ld returned 1 exit status at C