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
相关推荐
qq_349447958 分钟前
Linux系统,安装git,从使用git下载仓库(GitHub, Gitee, GitLab 等),并且使用ssh密钥,可以直接执行git pull
linux·git·ssh
小小龙学IT19 分钟前
Boost.Beast 深度实战:基于 Asio 的开源 C++ HTTP/WebSocket 协议库
c++·websocket·http
caimouse35 分钟前
ReactOS 图形系统分析(16):字符串对象 — STROBJ(string.c)
c语言·开发语言
饼饼学习空间智能1 小时前
家庭服务机器人训练数据怎么积累?仿真、真实采集与持续学习的技术路线分析
人工智能·算法·机器学习
Aphelios3801 小时前
一次锁内网络IO引发的Tomcat线程池“饿死”事故
java·开发语言·spring boot·elasticsearch·tomcat·网络io阻塞·线程池耗尽
不可求~1 小时前
C++ std::string_view 不是字符串:从悬空引用到安全用法
java·开发语言·c++
Lam Tang1 小时前
APS 系列文章10
java·代理模式