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
相关推荐
范什么特西8 小时前
网络代理问题
java·linux·服务器
AI科技星8 小时前
全域谱分析:无穷维超复数信息场分形统一场论——自然、量子、金融多重分形第一性原理完整体系(中英双语终稿)
人工智能·python·算法·金融·乖乖数学·全域数学
三月不知肉味y8 小时前
2026-07-05-JAVA面试场景题训练
java·开发语言·面试
utf8mb4安全女神8 小时前
【Redis数据库】哨兵集群/redis集群/安装配置/主从复制/数据持久化操作/数据结构/安全限制/PHP redis/
linux·服务器·数据结构·数据库·redis·缓存
豆瓣鸡8 小时前
封装 API 请求日志切面——从注解定义到 Starter 自动装配
java·开发语言·spring boot
Zk.Sun9 小时前
Linux设置触屏双击距离容差
linux·运维·数据库
先吃饱再说9 小时前
为什么堆能 O(log n) 插入?拆解完全二叉树的数组魔法
算法·排序算法
掉鱼的猫9 小时前
把 OpenAPI 接入 Agent Harness:零代码让 Agent 听懂你的 REST API
java·llm·agent
bukeyiwanshui9 小时前
20260622 安装配置ubuntu
linux·运维·ubuntu
lzhcoder9 小时前
Spring Boot 集成 Kafka:先跑通 Demo,再避开那 80% 的人踩过的坑
java·kafka