正在初始化数据文件中的静态常量成员
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";
}
相关文章:
- 私有类型的静态常量成员
- 分离一个静态常量 std::thread?
- 从另一个静态常量数组初始化静态常量数组(只需少量计算)
- 我可以在运行时重新定义在 OpenCascade/OCCT 标头中定义的 c++ 静态常量吗?
- 如何为静态常量模板化专用整数值分配存储
- 使用什么代替"静态常量 TCHAR *"
- C++ 模板中的静态常量初始化顺序
- 如何在编译时解析静态常量 std::string?
- 关于静态常量数据模因的声明和定义的混淆
- 将 static_cast<int>(-15) 分配给静态常量字符类型变量
- 为什么在第二类中使用静态常量会在第一类中给出编译器错误?
- 静态常量与常量局部变量,哪一个性能更好
- 如何在模板类中设置静态常量变量
- public:静态常量字符串声明/初始化问题
- 有没有办法声明一个公共静态常量,该常量将使用 constexpr 在源文件中定义(有什么区别)?
- 对静态常量积分类型的未定义引用
- 全局变量中的静态常量与常量
- c++ 类中的静态常量变量和常量变量在存储方面是否有区别
- 避免在静态常量类上定义但不使用
- 指向静态常量对象的共享指针?