const关键字
- C语言中const用法回顾
(1)const变量,比宏定义的优势是带数据类型,可以让编译器帮我们做类型检查
(2)const数组,和常量变量类似
(3)const指针,三种情况:const int *p, int * const p, const int *const p;
const int *p:P所指向的空间是不能被修改的
int * const p:P指针本身不能修改,类似引用,本身不能就该,但是指向的内容可以修改
const int *const p:前两个的结合 - C++中const新增用法
(1)const引用,主要用于函数传参,限制函数内部对实参进行修改
(2)const成员函数,限制函数内部对类的成员变量的修改
// 比较传入的数,大于100就返回0,小于等于100就返回-1
int func(int a)
{
if (a > 100)
return 0;
else
return -1;
}
// 要求传地址,形参定义时加const是为了告知所有人(负责实现函数的,调用该函数的,编译器),func1函数内不会修改传参pa所指向
// 的实际值(实参)
// 调用时,int i; func1(const_cast<const int *>(&i));
int func1(const int *pa)
{
if (*pa > 100)
return 0;
else
return -1;
}
// C++中更倾向于使用引用而不是指针
// 调用时,int i; func2(i);
int func2(const int &a)
{
if (a > 100)
return 0;
else
return -1;
}
class A
{
public:
int i;
int j;
int func8(int &a); // 这样写,隐含意思就是func8内部很有可能会修改传参a的值
int func9(const int &a); // 这样写,隐含意思就是func9内部不会改变a的值
int func10(int a) const; // const成员,明确告知func10内部不会修改class A
// 的成员变量的值
};
class test001 {
public:
int i;
int func6(void) const;
};
int test001::func6(void) const {
// this->i = 5;
cout << "test001::func6, i = " << this->i << endl;
}
int test(void) {
test001 a;
a.i = 1;
a.func6();
cout << "a.i = " << a.i << endl;
return 0;
}
mutable
(1)mutable用来突破const成员函数的限制,让其可以修改特定的成员变量
(2)案例参考:https://www.cnblogs.com/yongdaimi/p/9565996.html
#include
class Person {
public:
Person();
~Person();
int getAge() const; /*调用方法*/
int getCallingTimes() const; /*获取上面的getAge()方法被调用了多少次*/
private:
int age;
char *name;
float score;
mutable int m_nums; /*用于统计次数*/
};
Person::Person()
{
m_nums = 0;
}
Person::~Person(){}
int Person::getAge() const
{
std::cout << "Calling the method" << std::endl;
m_nums++;
// age = 4; 仍然无法修改该成员变量
return age;
}
int Person::getCallingTimes()const
{
return m_nums;
}
int test062402()
{
Person *person = new Person();
for (int i = 0; i < 10; i++) {
person->getAge();
}
std::cout << "getAge()方法被调用了" << person->getCallingTimes() << "次" << std::endl;
delete person;
// getchar();
return 0;
}
constexpr
(1)用法如下:
constexpr int multiply (int x, int y)
{
return x * y;
}
const int val = multiply( 10, 10 ); // 将在编译时计算
const int val = 100;
编译时就展开了
(2)本质上是让程序利用编译时的计算能力,增加运行时效率
(3)由C++11引入,但是实际有一些编译器并不支持,需实际测试
C++20新引入的2个
(1)constinit https://zh.cppreference.com/w/cpp/language/constinit
(2)consteval https://zh.cppreference.com/w/cpp/language/consteval
总结:
const的使用方法
了解mutable、constexpr、constinit 、consteval
学习记录,侵权联系删除。
来源:朱老师物联网大课堂