区别
**C语言的const是定义了一个const变量,该变量只具备读的功能,而不具备写的功能。
**C++的const是定义了一个常量。
c++中,const可以修饰类的成员函数,但在c中,不能修饰函数。
c++中,被修饰的类的成员函数,实际修饰隐含的this指针,表示在类中不可以对类的任何成员进行修改
#include <stdio.h>
//c语言
int main()
{
const int a = 10;
int* p = NULL;
printf("%d\n", a);
p = (int*)&a;
*p = 20;
printf("%d\n", a);
}
显然a的值发生变化,第一次输出是10,第二次是20
#include <iostream>
using namespace std;
//c++
int main()
{
const int a = 10;
int* p = NULL;
cout << << a << endl;
p = (int*)&a;
*p = 20;
cout <<<< a << endl;
return 0;
}
两次都输出了10
**可以发现,c语言中被const修饰的变量虽然不能直接修改,但是可以间接的通过指针修改,在c++中不能修改被cosnt修饰的变量。
C++编译器对const常量的处理当碰见常量声明时,在符号表中放入常量;编译过程中若发现使用常量则直接以符号表中的值替换。编译过程中若发现对const使用了extern或者&操作符,则给对应的常量分配存储空间(为了兼容C)。C++编译器虽然可能为const常量分配空间(进行&运算时候),但不会使用其存储空间中的值。
class Date
{
public:
Date(int year = 2018, int month = 6, int day = 23)
: _year(year)
, _month(month)
, _day(day)
{}
const int& GetDay()const //被const修饰后,this指针类型从Date* const this-->const Date* const this
{
return _day;
}
private:
int _year;
int _month;
int _day;
};
int main()
{
Date d1;
cout << d1.GetDay() << endl;
}
***上面的Getday()方法中,如果确实想要修改某个成员变量的值,也不是不可以,可以在想要修改的成员变量前加mutable关键字。
本文详细对比了C语言和C++中const关键字的行为差异,解释了C++如何更严格地保护const变量,以及const在C++类成员函数中的特殊用法。
312

被折叠的 条评论
为什么被折叠?



