[英]initializing static const member from data file
对于以下代码:
class A
{
public:
static const int VAL;
};
我知道我可以在类声明中为VAL分配一个值:
class A
{
public:
static const int VAL = 3;
};
或在CPP文件中:
const int A::VAL = 3;
但我想从数据文件中读取值。 我现在有一个函数,我们称之为F(),它读入我想要的值:
void F()
{
int value = ReadValueFromDataFile();
//But I can't do this:
const int A::VAL = value; //member cannot be defined in the current scope
}
如何根据从数据文件中读取的值来分配VAL的值?
在它们的定义(而不是它们的声明)中,使用函数调用的返回值初始化变量。
#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";
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.