在頭文件的類的定義中定義了一個const成員變量
C++ 規則:
1、類定義中不能進行初始化,因爲頭文件中類的定義只是一個聲明,並沒有分配真正空間,因此變量是不存在的,因此是不能賦值的。
2、const 定義的變量是不能賦值
這可如何是好,聲明中不能賦值,聲明完還不能賦值。又不能不賦值。
解決方案:
1、在構造函數後的參數初始化列表中初始化
2、將const變量同時聲明爲 static 類型進行初始化。
#include <iostream>
class TestA
{
public:
TestA(): m_iSIZE(20) {} // method 1
~TestA(){}
int GetSize()
{
return m_iSIZE;
}
private:
const int m_iSIZE;
};
class TestB
{
public:
TestB(){}
~TestB(){}
int GetSize()
{
return m_iSIZE;
}
private:
static const int m_iSIZE;
};
const int TestB::m_iSIZE = 3; // method 2
int main()
{
TestA oTestA;
TestB oTestB;
std::cout << "oTestA:" << oTestA.GetSize() << std::endl;
std::cout << "oTestB:" << oTestB.GetSize() << std::endl;
return 0;
}