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

一 const 成员变量

const 成员变量的用法和普通 const 变量的用法相似,只需要在声明时加上 const 关键字。初始化 const 成员变量只有一种方法,就是通过参数初始化表

二 const 成员函数

const 成员函数可以使用类中的所有成员变量,但是不能修改成员变量,这种措施主要还是为了保护数据而设置的。const 成员函数也称为常成员函数。

常成员函数需要在声明和定义的时候在函数头部的结尾都加上 const 关键字,如:

class Student{
public:
Student(char *name, int age, float score);
void show();
//声明常成员函数
char *getname() const;
int getage() const;
float getscore() const;
private:
char *m_name;
int m_age;
float m_score;
}; Student::Student(char *name, int age, float score): m_name(name), m_age(age), m_score(score){ }
void Student::show(){
cout<<m_name<<"的年龄是"<<m_age<<",成绩是"<<m_score<<endl;
}
//定义常成员函数
char * Student::getname() const{
return m_name;
}
int Student::getage() const{
return m_age;
}
float Student::getscore() const{
return m_score;
}

三.const对象

一旦将对象定义为const 对象之后,不管是哪种形式,则该对象就只能访问被 const 修饰的成员了(包括 const 成员变量const 成员函数),因为非 const 成员可能会修改对象的数据(编译器也会这样假设),C++禁止这样做。

例:

#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 *m_name;
int m_age;
float m_score;
}; Student::Student(char *name, int age, float score): m_name(name), m_age(age), m_score(score){ }
void Student::show(){
cout<<m_name<<"的年龄是"<<m_age<<",成绩是"<<m_score<<endl;
}
char * Student::getname() const{
return m_name;
}
int Student::getage() const{
return m_age;
}
float Student::getscore() const{
return m_score;
} int main(){
const Student stu("小明", , 90.6);
//stu.show(); //error
cout<<stu.getname()<<"的年龄是"<<stu.getage()<<",成绩是"<<stu.getscore()<<endl; const Student *pstu = new Student("李磊", , 80.5);
//pstu -> show(); //error
cout<<pstu->getname()<<"的年龄是"<<pstu->getage()<<",成绩是"<<pstu->getscore()<<endl; return ;
}

最新文章

  1. MySQL中有关TIMESTAMP和DATETIME的总结
  2. Form表单(回车)提交问题
  3. pdo mysql错误:Cannot execute queries while other unbuffered queries are active
  4. PHP 弹出文件下载
  5. Struts2入门2 Struts2深入
  6. IntelliJ IDEA 的 Java 热部署插件 JRebel 安装及使用
  7. Codeforces Round #284 (Div. 1)
  8. char和QChar(Unicode的编码与内存里的值还不是一回事)
  9. SignalR系列教程:在MVC5中使用SignalR
  10. 结构-行为-样式-Bootstrap笔记
  11. SQL注入之Sqli-labs系列第一篇
  12. java异常处理之throw, throws,try和catch
  13. AngularJS进阶(二十九)AngularJS项目开发技巧之localStorage存储
  14. DSAPI 截取被遮挡的窗口图像
  15. Tensorflow的验证码识别
  16. Android Studio 基础控件使用
  17. IDEA或者WebStorm关闭JS文件的黄色提示
  18. Android数据库大批量数据插入优化
  19. Redux 笔记详解
  20. RockerMQ消息消费、重试

热门文章

  1. POJ 2186 Popular Cows(强连通分量)
  2. 【2-SAT】【并查集】ICM Technex 2017 and Codeforces Round #400 (Div. 1 + Div. 2, combined) D. The Door Problem
  3. jdk8中Spliterator的作用
  4. 【MySQL笔记】MySql5安装图解教程
  5. 从最简单的vector中sort用法到自定义比较函数comp后对结构体排序的sort算法
  6. log4j在Web项目中的使用
  7. 使用Vue-cli创建project遇到的坑
  8. easyui textbox获取焦点事件
  9. Easyui datagrid 隐藏多选框 checkbox
  10. css3动画和JS+DOM动画和JS+canvas动画比较