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
相关推荐
Zhou141136几秒前
SpringBoot_02_自动配置原理
java·spring boot·后端
m0_380743874 分钟前
PHP7.3和7.2字符串功能有什么不同
开发语言·php
FYKJ_20107 分钟前
SSM校园失物招领系统41452-计算机课程设计、毕业设计
java·vue.js·spring boot·python·mysql·typescript·spark
kv11011 分钟前
Android studio国内开发有关
java·数据库·android studio
美狐美颜SDK开放平台12 分钟前
Android与iOS直播APP美颜有什么区别?视频美颜SDK开发详解
android·ios·音视频·视频美颜sdk
All for pursuit.30 分钟前
【分治-3】347.前K个高频元素
数据结构·c++·算法·leetcode
SuperByteMaster33 分钟前
低功耗GPIO引脚配置
c语言
卓怡学长36 分钟前
w198基于springboot始于足下健康打卡平台的设计与实现
java·spring boot·spring·intellij-idea
m0_3807438738 分钟前
PHP 8.4的新语法怎么用才规范
开发语言·php
头发够用的程序员42 分钟前
TensorRT 自定义算子插件实战(一):从零手写 customScaledTanh
c++·人工智能·pytorch·python·深度学习·边缘计算·jetson