《c程序设计基础》qa-第七章-c程序设计基础.ppt

上传人:小飞机 文档编号:5896063 上传时间:2023-08-31 格式:PPT 页数:18 大小:661.50KB
返回 下载 相关 举报
《c程序设计基础》qa-第七章-c程序设计基础.ppt_第1页
第1页 / 共18页
《c程序设计基础》qa-第七章-c程序设计基础.ppt_第2页
第2页 / 共18页
《c程序设计基础》qa-第七章-c程序设计基础.ppt_第3页
第3页 / 共18页
《c程序设计基础》qa-第七章-c程序设计基础.ppt_第4页
第4页 / 共18页
《c程序设计基础》qa-第七章-c程序设计基础.ppt_第5页
第5页 / 共18页
点击查看更多>>
资源描述

《《c程序设计基础》qa-第七章-c程序设计基础.ppt》由会员分享,可在线阅读,更多相关《《c程序设计基础》qa-第七章-c程序设计基础.ppt(18页珍藏版)》请在三一办公上搜索。

1、C+程序设计基础,Q&A第七章北京邮电大学信通院方莉,=运算符重载,=运算符重载,4,const使用,const使用常量常指针指针常量常引用常对象常数据成员常成员函数,5,const使用,const使用常量:const float PI=3.14;常指针 const int*iPtr1;或 int const*iPtr2;指针常量:int*const iPtr3;常引用:const int,const使用,const 作用 可以定义const常量,例如:constintMax=100;intArrayMax;便于进行类型检查,例如:voidf(constinti).编译器就会知道i是一个常量,

2、不允许修改;可以保护被修饰的东西,防止意外的修改,增强程序的健壮性。例如上例,如果在函数体内修改了i,编译器就会报错;例如:voidf(constinti)i=10;/error!,const使用,const 作用 为函数重载提供了一个参考。classA.voidf(inti)./一个函数voidf(inti)const./上一个函数的重载.;,const使用,修饰一般常量,常数组,常对象修饰符const可以用在类型说明符前,也可以用在类型说明符后。例如:intconstx=2;或 constintx=2;intconsta5=1,2,3,4,5;或constinta5=1,2,3,4,5;c

3、lassA;constAa;或Aconsta;,const使用,修饰指针constint*A;或intconst*A;/const修饰指向的对象,A可变,A指向的对象不可变;int*constA;/const修饰指针A,A不可变,A指向的对象可变;constint*constA;/指针A和A指向的对象都不可变。,const使用,修饰引用constdouble,const使用,修饰类的成员函数:const修饰符也可以修饰类的成员函数,格式如下:classClassNamepublic:intFun()const;.;这样,在调用函数Fun时就不能修改类里面的数据。,const使用,修饰类的数据成

4、员:const修饰符也可以修饰类的数据成员,格式如下:class A private:const int size;const数据成员在某个对象的生存期内是常量,对整个类来说是可变的;const数据成员不能在类声明中初始化,只能在类的构造函数的初始化列表中进行。,13,const使用,class Aprivate:constintc3=7;/errorstaticintc4=7;/error staticconstfloatc5=7;/error.;,14,#include using namespace std;class Apublic:A(int i);void print();cons

5、t int/静态常数据成员在类外说明和初始化A:A(int i):a(i),r(a)/常数据成员只能通过初始化列表来获得初值,const使用,15,const使用,const放置的位置 const int b=500;int const b=500;1 const int*a=4,16,const使用,const使用如果const位于*的左侧,则const就是用来修饰指针所指向的变量,即指针指向为常量;如果const位于*的右侧,const就是修饰指针本身,即指针本身是常量。,17,const使用1和2的情况相同,都是指针所指向的内容为常量(const放在变量声明符的位置无关),这种情况下不允许对内容进行更改操作,如不能*a=3;3指针本身是常量,而指针所指向的内容不是常量,这种情况下不能对指针本身进行更改操作,如a+是错误的;4指针本身和指向的内容均为常量。5 fun1()为类的常成员函数。,18,const使用,常量 const float PI=3.14;#define PI 3.14 const常量有数据类型,编译器对其做类型安全检查,宏常量没有数据类型,程序中只做字符替换,编译器没有类型安全检查,一出现意想不到的错误。,

展开阅读全文
相关资源
猜你喜欢
相关搜索

当前位置:首页 > 生活休闲 > 在线阅读


备案号:宁ICP备20000045号-2

经营许可证:宁B2-20210002

宁公网安备 64010402000987号