2012-02-28 78 views
1

對於以下的代碼:初始化從數據文件中的靜態const成員

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的值根據從數據文件中讀取值?

+0

就像在第二個例子中一樣,它只適用於整型(非std :: string)。 – 2012-02-28 22:19:19

回答

3

在它們的定義中(而不是它們的聲明)用函數調用的返回值初始化變量。

#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"; 
} 
+2

只要注意初始化順序問題。 – 2012-02-28 22:56:29