介绍
- 常成员是什么
1.常成员关键词为:const
2.常成员有:常成员变量、常成员函数、常成员对象
- 常成员有什么用
1.常成员变量:用于在程序中定义不可修改内部成员变量的函数
2.常成员函数:只能够访问成员变量,不可以修改成员变量
(PS:凡是 mutable 修饰的成员变量,依然能够修改该成员变量)
3.常成员对象:只能调用它的常成员函数,而不能调用该对象的普通成员函数(PS:只能调用常函数)
- 常成员变量怎么用
(1).常成员变量必须赋值,且初始化后不能更改
(2).常成员变量赋值初始化:
1.要么声明时赋值
2.要么初始化表时进行赋值 - 常成员函数怎么用
(1).函数体前加上 const ,例子:const int foo(){}
修饰 函数本身;
(PS:只能够访问成员变量,不可以修改成员变量)
(2).函数体后 大括号前加上 const,例子: int foo()const{}
修饰 this指针;
(PS:凡是 this 指向的成员变量都不可以修改,只能访问) - 常成员对象怎么用
(1).常对象只能调用常函数
(2).被 const 修饰的对象,对象指针 or 对象引用,统称为“常对象”
源码
#include<iostream>
#include<string>using namespace std;class Socre
{
public:Socre(int c) :Sum_socre(c), S_sumber(c){}~Socre(){}void foo(){cout << "正常函数" << endl;}void foo()const{cout << "常函数" << endl;}void Sfoo(int b)const{b = 30;cout << "const Sum_socre = " << this->Sum_socre << endl;cout << "mutable S_sumber = " << ++this->S_sumber << endl;cout << "b = " << b << endl;}
private:const int Sum_socre;mutable int S_sumber;
};int main()
{cout << "-------------正常对象版本-------------" << endl;Socre sumber(50);sumber.Sfoo(100);sumber.Sfoo(80);sumber.Sfoo(60);sumber.foo();cout <<"-------------常对象版本-------------"<< endl;const Socre sumber2(50);sumber2.Sfoo(90);sumber2.Sfoo(100);sumber2.Sfoo(700);sumber2.foo();system("pause");return 0;
}
运行结果
-------------正常对象版本-------------
const Sum_socre = 50
mutable S_sumber = 51
b = 30
const Sum_socre = 50
mutable S_sumber = 52
b = 30
const Sum_socre = 50
mutable S_sumber = 53
b = 30
正常函数
-------------常对象版本-------------
const Sum_socre = 50
mutable S_sumber = 51
b = 30
const Sum_socre = 50
mutable S_sumber = 52
b = 30
const Sum_socre = 50
mutable S_sumber = 53
b = 30
常函数
请按任意键继续. . .
笔记扩充
new 存储示意图:

源码
#include<iostream>
#include<string>using namespace std;class A
{
public:A(){ cout << "A构造" << endl; }~A(){ cout << "A析构" << endl; }};int main()
{A *pa = new A[3];cout << *((int*)pa-1) << endl;delete[] pa;system("pause");return 0;
}