C++语言基础(6)-const 关键字
2024-08-23 19:53:13
在类中,如果你不希望某些数据被修改,可以使用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 ;
}
最新文章
- MySQL中有关TIMESTAMP和DATETIME的总结
- Form表单(回车)提交问题
- pdo mysql错误:Cannot execute queries while other unbuffered queries are active
- PHP 弹出文件下载
- Struts2入门2 Struts2深入
- IntelliJ IDEA 的 Java 热部署插件 JRebel 安装及使用
- Codeforces Round #284 (Div. 1)
- char和QChar(Unicode的编码与内存里的值还不是一回事)
- SignalR系列教程:在MVC5中使用SignalR
- 结构-行为-样式-Bootstrap笔记
- SQL注入之Sqli-labs系列第一篇
- java异常处理之throw, throws,try和catch
- AngularJS进阶(二十九)AngularJS项目开发技巧之localStorage存储
- DSAPI 截取被遮挡的窗口图像
- Tensorflow的验证码识别
- Android Studio 基础控件使用
- IDEA或者WebStorm关闭JS文件的黄色提示
- Android数据库大批量数据插入优化
- Redux 笔记详解
- RockerMQ消息消费、重试
热门文章
- POJ 2186 Popular Cows(强连通分量)
- 【2-SAT】【并查集】ICM Technex 2017 and Codeforces Round #400 (Div. 1 + Div. 2, combined) D. The Door Problem
- jdk8中Spliterator的作用
- 【MySQL笔记】MySql5安装图解教程
- 从最简单的vector中sort用法到自定义比较函数comp后对结构体排序的sort算法
- log4j在Web项目中的使用
- 使用Vue-cli创建project遇到的坑
- easyui textbox获取焦点事件
- Easyui datagrid 隐藏多选框 checkbox
- css3动画和JS+DOM动画和JS+canvas动画比较