标签:关键帧 const 10 int value C++ test 指针
修饰普通变量,表示不可修改
#include <iostream>
using namespace std;
const int a1 = 10;
int main()
{
const int a2 = 10;
a1 = 10; // 错误,不可修改变量的值
int b1 = a1; // 可以给其余变量赋值
}
修饰指针
const修饰指针时分3种情况:常量指针、指针常量、常指针常量。
常量指针
#include <iostream>
using namespace std;
int main()
{
int a = 10;
// 常量指针,指针指向对象的值不能变,指针指向的对象可以变
const int* ptr = &a;
*ptr = 100; //错误
int b = 100;
ptr = &b; // 正确
}
指针常量
#include <iostream>
using namespace std;
int main()
{
int a = 10;
// 指针常量,指针指向的对象不可以变,指向对象的值可以变
int* const ptr = &a;
*ptr = 100; // 正确
int b = 100;
ptr = &b; // 错误
}
常指针常量
#include <iostream>
using namespace std;
int main()
{
int a = 10;
// 常指针常量,指针指向的对象、指向对象的值都不能变
const int* const ptr = &a;
*ptr = 100; // 正确
int b = 100;
ptr = &b; // 错误
}
const用于函数中
修饰函数的形参
表示函数中不能改变该形参的值。
#include <iostream>
using namespace std;
void function(const int a)
{
cout<<a<<endl;
a++;// 错误,a用const修饰,大小不能改变
}
int main()
{
int a = 10;
function(a);
}
修饰函数中的指针形参
防止意外修改指针指向对象的值。
#include <iostream>
using namespace std;
void function(const int* a,int* const b)
{
int temp = 100;
*a = 10; // 错误
a = &temp; // 正确
b = &temp; // 错误
*b = 20; // 正确
}
int main()
{
int a = 10;
int b = 10;
function(&a,&b);
}
修饰成员函数
const修饰成员函数时,表示成员函数中成员变量不能修改。
#include <iostream>
using namespace std;
class test
{
public:
test(int value):m_value(value){}
test(){}
~test(){}
void print_value() const
{
//this->m_value = 100; // 错误,const修饰成员函数中,不能修改成员变量的值
cout<<this->m_value<<endl;
}
const int get_value()
{
return this->m_value;
}
private:
int m_value;
};
int main()
{
test Test(20);
int value = Test.get_value();
cout<<value<<endl;
}
如果想让const成员变量可以在成员函数中修改的话,可以加一个关键字mutable。
#include <iostream>
using namespace std;
class test
{
public:
test(int value):m_value(value){}
test(){}
~test(){}
void print_value() const
{
this->m_value = 100; // 错误,const修饰成员函数中,不能修改成员变量的值
cout<<this->m_value<<endl;
}
const int get_value()
{
return this->m_value;
}
private:
mutable int m_value;
};
int main()
{
test Test(20);
int value = Test.get_value();
Test.print_value();
cout<<value<<endl;
}
参考文章:
https://www.runoob.com/w3cnote/cpp-const-keyword.html
标签:关键帧,const,10,int,value,C++,test,指针 来源: https://blog.csdn.net/weixin_43828675/article/details/114591136
本站声明: 1. iCode9 技术分享网(下文简称本站)提供的所有内容,仅供技术学习、探讨和分享; 2. 关于本站的所有留言、评论、转载及引用,纯属内容发起人的个人观点,与本站观点和立场无关; 3. 关于本站的所有言论和文字,纯属内容发起人的个人观点,与本站观点和立场无关; 4. 本站文章均是网友提供,不完全保证技术分享内容的完整性、准确性、时效性、风险性和版权归属;如您发现该文章侵犯了您的权益,可联系我们第一时间进行删除; 5. 本站为非盈利性的个人网站,所有内容不会用来进行牟利,也不会利用任何形式的广告来间接获益,纯粹是为了广大技术爱好者提供技术内容和技术思想的分享性交流网站。