const关键字的四种用法

1.修饰变量说明改变量不可以被改变

int a = 10;
const int b = 10; 
a = 20;
b = 20;//error! variable 'b' was declared const type

2.修饰指针,分为指向常量的指针和指针常量
指针常量:理解为一个指针类型的常量(不可以修改),即指针的指向的地址不可以修改,地址中存储的值可以修改

int a,b;
int  * const  p = &a;//这里注意写法,理解了指针常量是指针不可以修改,所以const应该在指针变量P的前面,在指针声明符*的后面,如果是常量指针声明则是const修饰常量,你可以理解成const将(*p)修饰了,所以指针的地址可以改变,而对应地址的值不能改变。
*p = 10;//success
p = &b;//error

常量指针:理解为一个指向常量的指针,即被该指针指向的地址,其储存的值不可以被修改,但常量指针本身可以指向不同的地址

int a,b;
int const * p = &a;
*p = 10;//error
p = &b;//success

3.常量引用,经常用于形参类型,即避免了拷贝,又避免了函数对值的修改;
在C++编程中,可以使用引用来传递参数

#include<stdio.h>

void functionA(int a); 
void functionB(const int &b);

int main()
{
    int a = 10; 
    const int b = 100;
    printf("a:%p--b:%p\n",&a,&b);

    functionA(a);
    functionB(b);
    return 0;
}

void functionA(int a)
{
    printf("a:%p,value = %d\n",&a,a);
}

void functionB(const int &b) 
{
    printf("b:%p,value = %d\n,",&b);
    b+=1;//错误,不能再函数内部修改变量的值
}

观察运行结果可以发现,引用确实是直接引用地址,而非“值传递”

a:0x7ffeec4f34f8--b:0x7ffeec4f34f4
a:0x7ffeec4f34dc,value = 10
b:0x7ffeec4f34f4,value = 515

4.修饰成员函数,说明该成员函数内不能修改成员变量

#include<iostream>

using namespace std;

class A{
public:
    A(){str="hello world!";};
    string  getValue() const
    {   
        cout<<str<<endl;
        str="ni hao!";//error!尝试修改成员变量的值
        return str;    
    }   

private:
    string str;
};

int main()
{
    A a;
    a.getValue();
}

猜你喜欢

转载自blog.csdn.net/weixin_33735676/article/details/86988137