6. C++ 中的cosnt
来源:小Q_wang     阅读:751
源码超市
发布于 2019-06-11 01:41
查看主页

在类中,假如你不希望某些数据被修改,可以使用const关键字加以限定。const 可以用来修饰成员变量和成员函数。

6.1 const成员变量

const 成员变量只要要在公告时加上 const 关键字。
初始化 const 成员变量只有一种方法,就是通过构造函数的初始化列表。


6.2 const成员函数(常成员函数)

const 成员函数可以使用类中的所有成员变量,但是不能修改它们的值,这种措施主要还是为了保护数据而设置的。
我们通常将 get 函数设置为常成员函数。读取成员变量的函数的名字通常以get开头,后跟成员变量的名字,所以通常将它们称为 get 函数。
常成员函数需要在公告和定义的时候在函数头部的结尾加上 const 关键字,例如:

#include <iostream>using namespace std;class Student{public:    Student(char *name, int age, float score);    void show();    //公告常成员函数    char *getname() const;    int getage() const;    float getscore() const;private:    char *name;    int age;    float score;};Student::Student(char *name, int age, float score): name(name), age(age), score(score){ }void Student::show(){    cout<<name<<"的年龄是"<<age<<",成绩是"<<score<<endl;}//定义常成员函数char * Student::getname() const{    return name;}int Student::getage() const{    return age;}float Student::getscore() const{    return score;}int main() {    return 0;}

必需在成员函数的公告和定义处同时加上 const 关键字。

char *getname() constchar *getname()

是两个不同的函数原型,假如只在一个地方加 const 会导致公告和定义处的函数原型冲突。

注意:
1、函数开头的 const 用来修饰函数的返回值,表示返回值是 const 类型,也就是不能被修改,如const char * getname()。
2、函数头部的结尾加上 const 表示常成员函数,这种函数只能读取成员变量的值,而不能修改成员变量的值,如char * getname() const。


6.3 const对象(常对象)

定义常对象的语法和定义常量的语法相似:

const  类名  对象名(参数);类名  const 对象名(参数);

当然你也可以定义 const 指针:

const 类名 *变量 = new 类名(参数);类名 const *变量 = new 类名(参数);

实例

#include <iostream>using namespace std;class Student{public:    Student(char *name, int age, float score);public:    void show();    char *getname() const;    int getage() const;    float getscore() const;private:    char *name;    int age;    float score;};Student::Student(char *name, int age, float score): name(name), age(age), score(score){ }void Student::show(){    cout<<name<<"的年龄是"<<age<<",成绩是"<<score<<endl;}char * Student::getname() const{    return name;}int Student::getage() const{    return age;}float Student::getscore() const{    return score;}int main(){    const Student stu("豆豆", 12, 85.0);    //stu.show(); //error    cout<<stu.getname()<<"的年龄是"<<stu.getage()<<",成绩是"<<stu.getscore()<<endl;    const Student *pstu = new Student("哈哈", 16, 65.0);    //pstu -> show(); //error    cout<<pstu->getname()<<"的年龄是"<<pstu->getage()<<",成绩是"<<pstu->getscore()<<endl;    return 0;}![image.png](https://pic.songma.com/wenzhang/20190402/w4uhuxn0iz3234.png?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240)一旦将对象定义为常对象之后,该对象就只能访问被 const 修饰的成员了(包括 const 成员变量和 const 成员函数),由于非 const 成员可能会修改对象的数据(编译器也会怀疑)。
免责声明:本文为用户发表,不代表网站立场,仅供参考,不构成引导等用途。 系统环境 服务器应用
相关推荐
IP-guard 能断网禁用吗
Anaconda创立环境、删除环境、激活环境、退出环境
电商放大镜及动态边框效果
电脑硬盘怎么合并分区
Python Learning-文件解决
首页
搜索
订单
购物车
我的