c++ 类型转换

2.const_cast

#include<iostream>
#include<string>
using namespace std;

void change(const int* pt, int n)
{
    int* pc;

    pc = const_cast<int*>(pt);
    *pc += n;
}

int main(void)
{
    int pop1 = 38383;
    const int pop2 = 2000;

    cout << "popl,pop2:    " << pop1 << ", " << pop2 << endl;
    change(&pop1, -103);
    change(&pop2, -103);
    cout << "popl,pop2:    " << pop1 << ", " << pop2 << endl;
    
    cin.get();
    return 0;
}

输出

pop1的值改变了,但pop2的值没有改变,因为pop2的值是真正的const,而pop1,只是在change函数里,传入的时候被const限定不能修改值

原文地址:https://www.cnblogs.com/heben/p/9528321.html