José D.
José D.

Reputation: 4275

"Undefined reference" trying to reference an static field

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

Upvotes: 2

Views: 780

Answers (1)

smparkes
smparkes

Reputation: 14053

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

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

Upvotes: 3

Related Questions