const使用方法

const是一个C++语言的限定符,它限定一个变量不允许被改变。使用const在一定程度上可以提高程序的安全性和可靠性。另外,在观看别人代码的时候,清晰理解const所起的作用,对理解对方的程序也有一些帮助。

1. 修饰常量

用const修饰的变量是不可变的,(错误演示):

#include<iostream>
#include<stdlib.h>
using namespace std;

int main(void)
{
    const int x = 3; // int const x = 3,和前一种是等价的
    x = 5;             // 此时x是一个整型常量,不可修改,编译出错。
    system("pause");
    return 0;
}

2. 修饰指针

如果const位于 * 的左侧,则const就是用来修饰指针所指向的变量,即指针指向为常量;
如果const位于 * 的右侧,const就是修饰指针本身,即指针本身是常量。
因此,推荐使用int const* p,而不是使用const int* p(虽然两者意义完全一样),这样更容易理解。

#include<iostream>
#include<stdlib.h>
using namespace std;

int main(void)
{
    const int x = 3; 
    int const *p = &x; // const int *p 两者等价
    *p = 5; // 编译报错 
   p = 5; // 编译通过
system("pause"); return 0; }

如果const位于 * 的右侧,const就是修饰指针本身,即指针本身是常量。

#include<iostream>
#include<stdlib.h>
using namespace std;

int main(void)
{
    int x = 3; 
    int y = 5;
    int *const p = &x;

    *p = 10; // 编译通过
    p = &y;  // 编译报错

    system("pause");
    return 0;
}

3. 修饰引用

#include<iostream>
#include<stdlib.h>
using namespace std;

int main(void)
{
    int x = 3; 
    int y = 5;
    int const &z = x;
    z = 10; // 编译错误

    system("pause");
    return 0;
}

4. 修饰函数参数

用const修饰函数参数,传递过来的参数在函数内不可以改变。

#include<iostream>
#include<stdlib.h>
using namespace std;

void fun (const int &a,const int &b);

int main(void)
{
    int x = 3; 
    int y = 5;
    fun(x,y);
    cout << x << "," << y << endl;

    system("pause");
    return 0;
}

void fun (const int &a,const int &b)
{
    a = 10; // 编译出错
    b = 20; // 编译出错
}

 

猜你喜欢

转载自www.cnblogs.com/chuijingjing/p/9018924.html