【c++学习笔记】c语言中的const和c++中const的区别

区别一:

  • C语言的const是定义了一个const变量,该变量只具备读的功能,而不具备写的功能。
  • C++的const是定义了一个常量。
int main()
{
    const int a = 10;
    int arr[a];//在c++中,因为a已经是常量,但在c中仍是变量,会报错
}
  • 再看下面的代码
#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);
}

这里写图片描述

#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;
}

这里写图片描述

  • 从上面的代码很容易发现,c语言中被const修饰的变量虽然不能直接修改,但是可以间接的通过指针修改,在c++中不能修改被cosnt修饰的变量,这是怎么实现的呢?
    • C++编译器对const常量的处理当碰见常量声明时,在符号表中放入常量;编译过程中若发现使用常量则直接以符号表中的值替换。编译过程中若发现对const使用了extern或者&操作符,则给对应的常量分配存储空间(为了兼容C)。C++编译器虽然可能为const常量分配空间(进行&运算时候),但不会使用其存储空间中的值。

区别二:

  • 在c++中,const可以修饰类的成员函数,但在c中,不能修饰函数。
    • c++中,被修饰的类的成员函数,实际修饰隐含的this指针,表示在类中不可以对类的任何成员进行修改
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关键字。
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
    {
        _day++;
        return _day;
    }
private:
    int _year;
    int _month;
    mutable int _day;
};

猜你喜欢

转载自blog.csdn.net/virgofarm/article/details/80783265
今日推荐