C语言中const和C++中const关键字的区别

# include "iostream"

using namespace std;

struct Teacher
{
    char name[30];
    int age;
};

void operatorTeacher(Teacher *pT)
{
    cout << pT->age<<endl;

}

void operatorTeacher1(const Teacher *pT)     //pT本身可以修改,pT指向的空间不可以被修改
{
    cout << pT->age << endl;
    pT = NULL;
    //pT->age = 10;  错误

}

void operatorTeacher2(Teacher * const pT)       //pT本身不可以修改,pT指向的空间可以修改
{
    cout << pT->age << endl;
    //pT = NULL;                              //错误
}

    int main01()
    {

扫描二维码关注公众号,回复: 2588669 查看本文章

        Teacher A;
        A.age = 33;
        operatorTeacher1(&A);

        system("pause");
        return 0;


    }
    void main02()
    {
        const int a = 10;
        int *p = NULL;
        p = (int *)&a;
        *p = 20;      //此处通过指针p间接修改a的值,如果在C语言编译器中,则打印20!常量a被修改。所以C语言中const是一个                                   冒牌货
                                  //但是在c++中此处打印的结果依然是10. 所以c++中的const才是真正意义上的常量。
                                //  在c++中用const定义一个变量,这个变量将会被放到一个符号表中,没有给a分配空间!!!,当a在别的                                     文件中被调用时或者被指针简介访问时才会分配空间给他,但是这个空间中的值和常量a是两回事,通过                                  地址修改它不能真正的修改
                               //  符号表中的常量a!!!
        cout << a << endl;              
        

        system("pause");
    }

    void fun1()
    {
        #define a 1                              //  在fun1()中#define 定义的a=1; 可以在fun2()中使用,但是const定义的b则不行。
                                                         // 说明const关键字定义的变量是有作用域的!!!
        const int b = 2;
    }

    void fun2()
    {
        cout << a << endl;
        //cout << b << endl;
    }

    void main()
    {
        fun1();
        fun2();

        system("pause");

    }

猜你喜欢

转载自blog.csdn.net/zwt0112/article/details/81275753