C++ Primer(第四版)书上P157页有关于这个题目的解释:当使用非const对象初始化const对象的引用时,系统将非const对象转换为const对象。比如:
int i;
const int &j = i;//ok:convert non_const to reference to const int;
现在我的疑问是既然非const对象被转换为const对象了,为什么对其进行赋值操作还是合法的?
比如
#include<iostream>
using namespace std;
int main(){
int i;
//i=3;
const int &j= i;
i =20; //这句话为什么合法,i不是被转化为const对象了吗?
cout <<j<<" "<<i;//j,i都是20 - -!
system("pause");
return 0;
}
...全文
1684打赏收藏
用非const对象初始化const引用的后果?
C++ Primer(第四版)书上P157页有关于这个题目的解释:当使用非const对象初始化const对象的引用时,系统将非const对象转换为const对象。比如: int i; const int &j = i;//ok:convert non_const to reference to const int; 现在我的疑问是既然非const对象被转换为const对象了,为什么对其进行赋值操作还是合法的? 比如#include using namespace std; i