chap8 const

本文详细介绍了C++中const关键字的多种用途及其注意事项,包括const变量的内存分配、const指针和引用的特性、const成员函数的使用等。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

 #define VS. const
#define BUFSIZE 20              const int bufsize = 20;
  preprocess time compiler time
  no type checking   type checking


const变量没有放在内存中,放在符号表,编译时是文件内部链接,其他的文件不可见,一定要可见,需使用
extern,此时将分配空间

A const in C++ defaults to internal linkage; that is, it is visible only within the file
where it is defined and cannot be seen at link time by other translation units. You must
always assign a value to a const when you define it, except when you make an explicit
declaration using extern:

extern const int bufsize;

Normally, the C++ compiler avoids creating storage for a const, but instead holds the
definition in its symbol table. When you use extern with const, however, you force storage
to be allocated (this is also true for certain other cases, such as taking the address of
a const). Storage must be allocated because extern says “use external linkage,” which
means that several translation units must be able to refer to the item, which requires it
to have storage.

In the ordinary case, when extern is not part of the definition, no storage is allocated.
When the const is used, it is simply folded in at compile time.


const类型是否分配空间的情形:

Whether or not storage is reserved for a const in C++ depends on how it is used.
In general, if a const is used simply to replace a name with a value (just as you would
use a #define), then storage doesn’t have to be created for the const. If no storage is
created (this depends on the complexity of the data type and the sophistication of the
compiler), the values may be folded into the code for greater efficiency after type
checking, not before, as with #define. If, however, you take an address of a const (even
unknowingly, by passing it to a function that takes a reference argument) or you define it
as extern, then storage is created for the const.




(1)所指的内容不能改变,但是可以指向不同的地址
    const int* u;  
u is a pointer, which points to a const int.

no initialization is required because you’re
saying that u can point to anything (that is, it is not const), but the thing it points to
cannot be changed.

eg.  int k = 20;
    u = &k; //ok
    *u = 30;//illegal
   
    int i = 10;
    u = &i; //ok
    
(2)指针的地址不能指向其他地址,但是所指的内容可以改变
 int d=1; int* const u=&d;
u is a pointer, which is const, that points to an int.   
Because the pointer itself is now the const, the compiler requires that it be given an
initial value that will be unchanged for the life of that pointer.
     
eg.  *u = 20; //ok
    int j = 10;
    u = &j;//illegal


char* cp = "how"的问题
字符串"how"由编译器创建一个constant字符串数组,由首地址指引。而cp不是常指针,语法上
是不可以的,而是为了兼容C代码没有报错,这样也带来一个问题,任何修改这个字符串的行为
都将造成运行时错误,如cp[1] = 'i';//runtime error

解决的办法:
(1)不想cp指向的东西改变,使用const char* cp = "how";
(2)可能改变cp的内容,使用char cp[] = "how";




const type func(...)
For built-in types, it doesn’t matter whether you return by value as a const, so you
should avoid confusing the client programmer and leave off the const when returning a
built-in type by value.

Returning by value as a const becomes important when you’re dealing with user-defined
types. If a function returns a class object by value as a const, the return value of that
function cannot be an lvalue (that is, it cannot be assigned to or otherwise modified).

The reason const has no meaning when you’re returning a built-in type by value is that
the compiler already prevents it from being an lvalue (because it’s always a value, and
not a variable). Only when you’re returning objects of user-defined types by value does
it become an issue.




const in classes
Inside a class, const partially reverts to its meaning in C. It allocates storage within
each object and represents a value that is initialized once and then cannot change. The
use of const inside a class means “This is constant for the lifetime of the object.”
However, each different object may contain a different value for that constant.

eg.
class Fred {
 const int size;//必须在初始化列表里初始化
public:
 Fred(int sz);
 void print();
};

Fred::Fred(int sz) : size(sz) {}
void Fred::print() { cout << size << endl; }

int main() {
 Fred a(1), b(2), c(3);
 a.print(), b.print(), c.print();
} ///:~




static const type in classes
The static keyword, in this situation, means “there’s only one instance, regardless of
how many objects of the class are created,” which is precisely what we need here: a member
of a class which is constant, and which cannot change from one object of the class to
another. Thus, a static const of a built-in type can be treated as a compile-time constant.

eg.
class
{
static const int size = 100;//initialize in the class
}




const objects & const member functions
eg.
#include <iostream>
using namespace std;

//: C08:ConstMember.cpp
class X {
 int i;
public:
 X(int ii);
 int f() const;//const member func: can not modify member data
 void set();
};

X::X(int ii) : i(ii) {}
int X::f() const //!!!NOTE!!!: this "const" can not be omitted!
{ return i; }
void X::set(){i = 10;}

int main() {
 X x1(10);
 const X x2(20);
 x1.f();
 x2.f();

 x1.set();
//!  x2.set();//illegal:const object can only call const member functions
} ///:~
1. 用户与身体信息管理模块 用户信息管理: 注册登录:支持手机号 / 邮箱注册,密码加密存储,提供第三方快捷登录(模拟) 个人资料:记录基本信息(姓名、年龄、性别、身高、体重、职业) 健康目标:用户设置目标(如 “减重 5kg”“增肌”“维持健康”)及期望周期 身体状态跟踪: 体重记录:定期录入体重数据,生成体重变化曲线(折线图) 身体指标:记录 BMI(自动计算)、体脂率(可选)、基础代谢率(根据身高体重估算) 健康状况:用户可填写特殊情况(如糖尿病、过敏食物、素食偏好),系统据此调整推荐 2. 膳食记录与食物数据库模块 食物数据库: 基础信息:包含常见食物(如米饭、鸡蛋、牛肉)的名称、类别(主食 / 肉类 / 蔬菜等)、每份重量 营养成分:记录每 100g 食物的热量(kcal)、蛋白质、脂肪、碳水化合物、维生素、矿物质含量 数据库维护:管理员可添加新食物、更新营养数据,支持按名称 / 类别检索 膳食记录功能: 快速记录:用户选择食物、输入食用量(克 / 份),系统自动计算摄入的营养成分 餐次分类:按早餐 / 午餐 / 晚餐 / 加餐分类记录,支持上传餐食照片(可选) 批量操作:提供常见套餐模板(如 “三明治 + 牛奶”),一键添加到记录 历史记录:按日期查看过往膳食记录,支持编辑 / 删除错误记录 3. 营养分析模块 每日营养摄入分析: 核心指标计算:统计当日摄入的总热量、蛋白质 / 脂肪 / 碳水化合物占比(按每日推荐量对比) 微量营养素分析:检查维生素(如维生素 C、钙、铁)的摄入是否达标 平衡评估:生成 “营养平衡度” 评分(0-100 分),指出摄入过剩或不足的营养素 趋势分析: 周 / 月营养趋势:用折线图展示近 7 天 / 30 天的热量、三大营养素摄入变化 对比分析:将实际摄入与推荐量对比(如 “蛋白质摄入仅达到推荐量的 70%”) 目标达成率:针对健
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值