问题:类中是否能够定 const 成员?编程
下面的类定义是否合法?
若是合法, ci的值是什么,存储在哪里?函数
class Test { private: const int ci; public: int getCI() { return ci }; };
#include <stdio.h> class Test { private: const int ci; public: Test() { ci = 10; // ERROR } int getCI() { return ci; } }; int main() { Test t; printf("t.ci = %d\n", t.getCI()); return 0; }
输出: test.cpp:8: error: uninitialized member ‘Test::ci’ with ‘const’ type ‘const int’ test.cpp:10: error: assignment of read-only data-member ‘Test::ci’
- C++ 中提供了初始化列表对成员变量进行初始化
- 语法规则
Class::ClassName() : m1(v1), m2(v1, v2), m3(v3) { // some other initialize operator }
- 成员的初始化顺序与成员的声明顺序相同
- 成员的初始化顺序与初始化列表中的位置无关
- 初始化列表先于构造函数的函数体执行
#include <stdio.h> class Value { private: int mi; public: Value(int i) { printf("Value::Value(int i), i = %d\n", i); mi = i; } int getI() { return mi; } }; class Test { private: Value m2; Value m3; Value m1; public: Test() : m1(1), m2(2), m3(3) { printf("Test::Test()\n"); } }; int main() { Test t; return 0; }
输出: Value::Value(int i), i = 2 Value::Value(int i), i = 3 Value::Value(int i), i = 1 Test::Test() 结论: 成员的初始化顺序与成员的声明顺序相同; 初始化列表先于构造函数的函数体执行。
发生了什么?
构造函数的函数体执行前,对象已经建立完成。构造函数仅执行了对象状态的 ‘初始化’ (实质为赋值完成,非真正意义的初始化)。初始化列表用于初始化成员,必然在类对象建立的同时进行,而非对象构造好了才进行的初始化。code
- 类中的 const 成员会被分配空间(与对象分配的空间一致,堆、栈、全局数据区)
- 类中的 const 成员的本质是只读变量(不会进入符号表)
- 类中的const 成员只能在初始化列表中指定初始值
编译器没法直接获得 const 成员的初始值,所以没法进入符号表成为真正意义上的常量。对象
#include <stdio.h> class Test { private: const int ci; public: Test() : ci(100) { } int getCI() { return ci; } void 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; }
输出: t.ci = 100 t.ci = 10
初始化与赋值不一样ci
- 初始化: 对正在建立的对象(变量)进行初值设置
- 赋值: 对已经存在的对象(变量)进行值设置
void code() { int i = 10; // 初始化 // ... i = 1; // 赋值 }
- 类中能够使用初始化列表对成员进行初始化
- 初始化列表先于构造函数体执行
- 类中能够定义 const 成员变量
- const 成员变量必须在初始化列表中指定初值
- const 成员变量为只读变量
以上内容参考狄泰软件学院系列课程,请你们保护原创!get