//const_cast转换符是用来移除变量的const或volatile限定符
#include <iostream>
using namespace std;
void func(const int &a)
{
int b = const_cast<int &>(a);
b++;
cout << b <<endl;
}
int main()
{
int m=6;
func(m);
cout << m <<endl;
return 0;
}
结果输出:
7
6
因为在func中定义的b是个独立的变量,b和a是两个不同的内存单元。对b的变换,并不影响a。
变换一下,把func中的b改成引用
#include <iostream>
using namespace std;
void func(const int &a)
{
int &b = const_cast<int &>(a);
b++;
cout << b <<endl;
}
int main()
{
int m=6;
func(m);
cout << m <<endl;
return 0;
}
输出:
7
7
因为b是a引用,所以a和b指向同一个内存单元。
#include <iostream>
using namespace std;
int main()
{
const int m=6;
int &b = const_cast<int &>(m);
b++;
cout << b <<endl;
cout << m <<endl;
return 0;
}
输出:
7
6
#include <iostream>
using namespace std;
int main()
{
const int &m=6;
int &b = const_cast<int &>(m);
b++;
cout << b <<endl;
cout << m <<endl;
return 0;
}
输出:
7
7