问题:类中是否可以定义const成员?
无法在构造函数赋值的const成员
示例代码:类中的const成员
#include <stdio.h>
class Test
{
private:
const int ci;
public:
Test()
{
ci = 10;
}
int getCI()
{
return ci;
}
};
int main()
{
const int i = 10;
Test t;
printf("t.ci = %d\n", t.getCI());
return 0;
}
输出结果:
test.cpp:9: error: uninitialized member ‘Test::ci’ with ‘const’ type ‘const int’
test.cpp:11: error: assignment of read-only data-member ‘Test::ci’
分析:为什么会失败呢?
关键问题需要区分初始化和赋值这两个概念。
1. 初始化:对正在创建的对象进行初值设置
2. 赋值:对已经存在的对象进行值设置
我们知道:类中成员是不能初始化的,只能通过在构造函数里面给成员变量赋值。但是const变量只能初始化,赋值则会报错。
问题:既然不能在构造函数里赋值,那么我们该如何给const成员变量进行初始化呢?
构造函数的初始化列表
C++中提供了初始化列表对成员变量进行初始化。
示例代码:构造函数的初始化列表的使用
#include <stdio.h>
class Value
{
private:
int mi;
public:
Value(int i)
{
printf("i = %d\n", i);
mi = i;
}
int getI()
{
return mi;
}
};
class Test
{
private:
const int ci;
Value m2;
Value m3;
Value m1;
public:
Test() : m1(1), m2(2), m3(3), ci(100)
{
printf("Test::Test()\n");
}
int getCI()
{
return ci;
}
int setCI(int v)
{
int* p = const_cast<int*>(&ci);
*p = v;
}
};
int main()
{
Test t;
printf("t.ci = %d\n", t.getCI());
t.setCI(10);
printf("t.ci = %d\n", t.getCI());
return 0;
}
输出结果:
i = 2
i = 3
i = 1
Test::Test()
t.ci = 100
t.ci = 10
分析:
1. 构造函数的使用方法:ClassName::ClassName():m1(v1),m2(v1,v2),m3(v3)。
如:Test() : m1(1), m2(2), m3(3)。
- 根据输出结果来看:
a) 成员的初始化顺序与成员的声明顺序相同。
b) 成员的初始化顺序与初始化列表中的位置无关
c) 初始化列表先于构造函数的函数体执行
类中const成员的问题
问题:我们解决了const成员初始化的问题,那么const成员储存在哪里呢?是只读变量还是常量呢?
分析思路:我们知道真正意义上的常量是无法通过指针修改它的值得,而只读变量是可以通过指针修改其值得。
程序中我们可以用指针修改const成员变量的值,说明类中的const成员的本质是只读变量。
因为类中的const成员只能在初始化列表中指定初始值,所以编译器无法直接得到const成员的初始值,因此无法进入符号表成为真正意义上的常量。