【C++】C++ 类中的 this 指针用法 ② ( 常量成员函数 您所在的位置:网站首页 height身高的用法 【C++】C++ 类中的 this 指针用法 ② ( 常量成员函数

【C++】C++ 类中的 this 指针用法 ② ( 常量成员函数

2024-07-02 19:15| 来源: 网络整理| 查看: 265

一、常量成员函数1、const 修饰成员函数分析

在 C++ 类中 , 普通的非静态成员函数 , 可以使用 const 进行修饰 ,

在 下面的 Student 类中 , 定义了 void fun(int age, int height) 成员函数 , 下面使用 const 关键字修饰该类 ;

使用 const 修饰 成员函数 , 写法如下 , 在 fun() 之后使用 const 关键字修饰 函数 :

代码语言:javascript复制void fun(int age, int height) const

const 修饰的是 fun 函数的 第一个参数 Student* pThis 指针指向的内存空间 ;

C++ 编译器会将

代码语言:javascript复制void fun(int age, int height)

函数转为对应的 C 语言函数

代码语言:javascript复制Student_fun(Student* pThis, int age, int height)

使用 const 修饰函数 , 其本质是修饰 第一个参数 Student* pThis 指针指向的内存空间 和 指针本身 ;

代码语言:javascript复制void fun(int age, int height) const

转换为 C 语言代码为 :

代码语言:javascript复制void Student_fun(const Student* const pThis, int age, int height)

左数右指 , const 在 * 左边修饰的是内存中的数据, const 在 * 右边修饰的是指针本身 ;

代码示例 :

代码语言:javascript复制class Student { public: // 使用 const 修饰 类的成员函数 // const 关键字可以 // 在 void fun(int age, int height) 之后 , 大括号之前 , // void fun(int age, int height) const // // const 修饰的是 fun 函数的 第一个参数 Student* pThis 指针指向的内存空间 和 指针本身 // // C++ 编译器会将该函数转为 Student_fun(Student* pThis, int age, int height) // 使用 const 修饰函数 , 其本质是修饰 第一个参数 Student* pThis 指针指向的内存空间 // void Student_fun(const Student* pThis, int age, int height) // 左数右指 , const 在 * 左边修饰的是内存中的数据, const 在 * 右边修饰的是指针本身 void fun(int age, int height) const { //this->age = age; //this->height = height; } public: int age; // 年龄 int height; // 身高 };2、常量成员函数

使用 const 关键字 修饰成员函数 , 会将 成员函数 转化为 " 常量成员函数 " ;

" 常量成员函数 " 中 操作限制 :

不能修改成员变量 : 不能修改 任何 成员变量 值 , 静态成员变量 与 非静态普通成员变量 都不能修改 ;不能调用非常量成员函数 : 只能调用 " 常量成员函数 " , 不能调用 非常量成员函数 , 以保证不会修改 成员变量 ;

" 常量成员函数 " 只能访问

常量成员变量其它常量成员函数

如果类的 成员变量 不是 常量 , 那么 " 常量成员函数 " 不能访问它们 ;

代码语言:javascript复制public: int age; // 年龄 int height; // 身高

如果类的 成员变量 是 常量 , 那么 " 常量成员函数 " 可以访问它们 , 注意 : 只能访问 , 不能修改 ;

代码语言:javascript复制public: const int age; // 年龄 const int height; // 身高

如果 成员函数 被 const 关键字 声明为 常量成员函数 , 则在该函数中 不能修改 类对象中的 任何成员变量 ;

代码语言:javascript复制class Student { public: void fun(int age, int height) const { //this->age = age; //this->height = height; } public: int age; // 年龄 int height; // 身高 };3、错误代码示例 - 常量成员函数修改成员变量

错误代码示例 :

代码语言:javascript复制class Student { public: // 带参构造函数 Student(int age, int height) { this->age = age; this->height = height; cout hello_world.cpp 1>D:\002_Project\006_Visual_Studio\HelloWorld\HelloWorld\hello_world.cpp(33,7): error C3490: 由于正在通过常量对象访问“age”,因此无法对其进行修改 1>D:\002_Project\006_Visual_Studio\HelloWorld\HelloWorld\hello_world.cpp(34,7): error C3490: 由于正在通过常量对象访问“height”,因此无法对其进行修改 1>已完成生成项目“HelloWorld.vcxproj”的操作 - 失败。 ========== 生成: 成功 0 个,失败 1 个,最新 0 个,跳过 0 个 ==========在这里插入图片描述在这里插入图片描述二、完整代码示例

代码示例 :

代码语言:javascript复制#include "iostream" using namespace std; class Student { public: // 带参构造函数 Student(int age, int height) { this->age = age; this->height = height; cout


【本文地址】

公司简介

联系我们

今日新闻

    推荐新闻

    专题文章
      CopyRight 2018-2019 实验室设备网 版权所有