C&C++ 常量 #7
JAX1024Dev
started this conversation in
General
Replies: 0 comments
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Uh oh!
There was an error while loading. Please reload this page.
-
常量是一种标识符,它的值在运行期间恒定不变。
#define来定义常量,宏常量。#define还可以使用const来定义常量,const 常量。为什么需要常量
const #define 比较
const 有哪些优点?
常量定义规则
const float RADIUS = 100; const float DIAMETER = RADIUS * 2类与常量
有时我们需要某些常量只在类中有效,自然想到在类中用
const来修饰数据成员。这种用法的确存在,但其含义并不是此。const 数据成员
生存周期:const 数据成员只在某个对象生存期内是常量,对于整个类而言却是可变的,因为类可以创建多个对象,不同的对象中的 const 数据成员是可以不同的。
初始化:const 数据成员的初始化只能在类构造函数的初始化表中进行。
整个类中恒定的常量
虽然不能通过 cosnt 实现,但是我们可以使用枚举常量实现。
枚举常量不会占用对象的存储空间,在编译时就被全部求值。
缺点:隐含数据类型是整型,最大值有限。
Beta Was this translation helpful? Give feedback.
All reactions