C++ - 面向对象 - 常成员函数

常成员函数

1、基本介绍
  1. 函数后面跟个 const,是 C++ 的常成员函数语法

  2. 常成员函数不会修改任何成员变量(mutable 成员除外)

  3. 常成员函数不可以调用其他成员函数,可以调用其他常成员函数

  4. const 对象只能调用 const 函数

  5. 可以提供重载,普通对象优先调用非 const 版本

2、演示
  1. 基本使用
cpp 复制代码
class Student {
private:
	int age;
	mutable int cache;
public:

	int getAge() const {
		// age = 1; // 不能修改
		// cache = 1; // 可以修改
		// setAge(10); // 不能调用
		// setCache(10); // 可以调用
		return age;
	}

	void setAge(int a) {
		age = a;
	}

	void setCache(int c) const {
		cache = c;
	}
};
  1. const 对象只能调用 const 函数
cpp 复制代码
class Student {
private:
	int age = 10;
	mutable int cache;
public:
	int getAge() const {
		return age;
	}

	void setAge(int a) {
		age = a;
	}

	void setCache(int c) const {
		cache = c;
	}
};
cpp 复制代码
const Student s = Student();

cout << s.getAge() << endl; // 可以调用
s.setAge(10); // 不能调用
s.setCache(10); // 可以调用
  1. 可以提供重载,普通对象优先调用非 const 版本
cpp 复制代码
class Student {
private:
	int age = 10;
	mutable int cache;
public:
	int getAge() {
		age = 20;
		return age;
	}

	int getAge() const {
		return age;
	}

	void setAge(int a) {
		age = a;
	}

	void setCache(int c) const {
		cache = c;
	}
};
cpp 复制代码
Student s = Student();

cout << s.getAge() << endl;
复制代码
# 输出结果

20
相关推荐
zhangjin112025 分钟前
解决Android Studio gradle下载超时和缓慢问题(二)
android·ide·android studio
Highcharts.js6 小时前
教程:基于 React + Highcharts 构建一个单页应用程序、按需数据拉取与图表渲染
开发语言·前端·数据结构·react.js·前端框架·highcharts·页面应用
腾科IT教育6 小时前
Oracle认证怎么选?2026年OCP/OCM报考指南
linux·运维·华为认证·hcie·开闭原则·datacom
头发还在的女程序员7 小时前
医院陪诊管理系统怎么选择?——2026 年选型避坑与架构参考
java·开发语言·陪诊系统·陪诊app·医院陪诊陪护
王维同学7 小时前
Winsock 协议与名称空间 Provider 目录
网络·c++·windows·安全
CodeStats7 小时前
【Spring事务】Spring事务注解 @Transactional 完整体系:从 MySQL 隔离级别到 MyBatis 原理详解
java·spring·mybatis·事务·transactional
xingxiliang8 小时前
深入浅出 Android CTS 视频测试:从环境搭建、用例设计到底层通信原理
android·音视频
我命由我123458 小时前
Android 开发问题:为 PDFView 设置一个带有黑色边框的背景 drawable,但边框没有生效
android·java·java-ee·android studio·android jetpack·android-studio·android runtime
拳里剑气9 小时前
C++算法:BFS解决FloodFill算法
c++·算法·bfs·宽度优先