在头文件的类的定义中定义了一个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;
}