“Undefined reference” trying to reference an static field

 ̄綄美尐妖づ 提交于 2019-12-11 01:38:09

问题


I have this definition for my Test class:

#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[];
};   

When I try to use Test::outStream or Test::inStream, for example here:

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

I get this msg: "undefined reference to `Test::inStream'"

I have read something about inicializating the static members in the .cpp file, but I don't know how to do that with fstream's


回答1:


You need to define the streams where you define the other Test methods:

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


来源:https://stackoverflow.com/questions/9446365/undefined-reference-trying-to-reference-an-static-field

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!