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
相关推荐
Flynt3 小时前
升级Flutter 3.44,我踩了HCPP和AGP 9的坑
android·flutter·dart
AI人工智能+电脑小能手4 小时前
【大白话说Java面试题 第77题】【Mysql篇】第7题:回表查询与全表扫描的区别?
java·开发语言·数据库·mysql·面试
水木流年追梦4 小时前
大模型入门-大模型分布式训练2
开发语言·分布式·python·算法·正则表达式·prompt
菜鸟是大神4 小时前
07-Claude Code 的常用命令和快捷键
linux·运维·服务器
sali-tec4 小时前
C# 基于OpenCv的视觉工作流-章78-KRT测量
图像处理·人工智能·数码相机·opencv·算法·计算机视觉
hj2862514 小时前
Linux存储空间管理完整笔记
linux·运维·笔记
lulu12165440784 小时前
Claude Code SpringBoot技能体系架构设计与演进
java·人工智能·spring boot·后端·ai编程
白色牙膏4 小时前
Cocos Creator 2.4.x 接入 AdMob 插件的迁移实践
android
菜菜的顾清寒4 小时前
力扣HOT100(32)二叉树的中序遍历
数据结构·算法·leetcode
x2c4 小时前
数据结构:线性表中链表的建立和基本操作(C)
算法