C++中const大杂烩

1.普通变量被const修饰,在C语言中,是可读变量,不是真常量,应为可以通过指针来修改;但是在C++中,却是真常量,通过指针不能修改被const修饰的普通变量。

    const int i = 2;
    int* pi = (int*)&i;
    *pi = 4;   //C++中的const是真常量
    cout << "i: " << i << ",*pi: " << *pi << endl;

    const int* j = (int*)(&i);
    int* pj = const_cast<int*>(j); //C++中的const是真常量

    *pj = 6;
    cout << "i: " << i << ",*j: " <<*j <<",*pj: " << *pj << endl;

但是被volatile修饰的const那就不是真常量了,应为volatile会方式const常量进入符号表;

    const int x = 1;              //x进入符号表,绝对常量
    int& rx = const_cast<int&>(x);
    rx = 5;
    printf("x = %d,rx = %d\n",x,rx);

    volatile const int y = 2;     //volatile 的作用立马凸显:防止y进入符号表,使绝对常量变成只读常量
    int& ry = const_cast<int&>(y);
    ry = 6;
    printf("y = %d,ry = %d\n",y,ry);

2.在C++中,如果const 与引用一起修饰普通变量,那么结果就大不一样了。
有两种特点:
1>const引用可以被常量初始化;
2>const引用可以通过指针来修改,即const引用让普通变量拥有只读属性。

    const int& j = 1;
    int& k = const_cast<int&>(j);

    const int x = 2;
    int& y = const_cast<int&>(x);

    k = 3;
    cout << "j: " << j << ",k: " << k << endl;


    y = 4;
    cout << "x: " << x << ",y:" << y << endl;
    const int& i = 2;  //C++中使用const引用就能使得常量ci变成只读变量
    int* pi = (int*)&i;

    *pi = 14;
    cout << "i: " << i << ",*pi: " << *pi << endl;

3.当函数返回值为引用时
1>若返回栈变量
(1)不能成为其它引用的初始值;
(2)不能作为左值使用;

int& test_041()
{
    int i = 21;
    return i;
}
void test_04()
{
    int& i = test_041();  //变量i可能会产生随机值
    cout << "i: " << i << endl;
}

2>若返回静态变量或全局变量
(1)可以成为其它引用的初始值;
(2)既可以做右值使用,也可以做左值使用。

int& test_031()
{
    static int ret = 1;

    return ret;
}
void test_03()
{
    test_031() = 2;      //引用作为返回值时,当返回静态变量或全局变量时,可以作为左值使用
    cout << test_031() << endl;

    int i = test_031();  //引用作为返回值时,当返回静态变量或全局变量时,可以作为右值使用
    cout << "i: " << i << endl;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值