Reputation: 1608
For the following code:
class A
{
public:
static const int VAL;
};
I know that I can assign VAL a value in the class declaration:
class A
{
public:
static const int VAL = 3;
};
or in the CPP file:
const int A::VAL = 3;
But I would like to read the value in from a data file. I have a function now, let's call it F() which reads in the value I want:
void F()
{
int value = ReadValueFromDataFile();
//But I can't do this:
const int A::VAL = value; //member cannot be defined in the current scope
}
How can I assign the value of VAL based on a value read in from a data file?
Upvotes: 1
Views: 649
Reputation: 168696
At their definition (not their declaration) initialize the variables with the return value of a function call.
#include <fstream>
#include <iostream>
class A
{
public:
static const int VAL1;
static const int VAL2;
};
int F(const char*);
// If you need to separate .H from .CPP, put the lines above
// in the .H, and the lines below in a .CPP
const int A::VAL1 = F("1.txt");
const int A::VAL2 = F("2.txt");
int F(const char* filename)
{
std::ifstream file(filename);
int result = 0;
file >> result;
return result;
}
int main () {
std::cout << A::VAL1 << " " << A::VAL2 << "\n";
}
Upvotes: 3