const的引用,语法问题。在c++ primer 中文版(第四版.特别版)的62页的术语中const 引用(const refrence) 可
const的引用,语法问题。
在c++ primer 中文版(第四版.特别版)的62页的术语中
const 引用(const refrence) 可以绑定到const对象,非const对象或右值的引用。
const 引用不能改变与其相关联的对象。
在下面的代码中,如果const 引用不能改变与其相关联的对象,那么输出的a的值应该是0才对。用vs2010编译通过后,a的值输出为5
- C/C++ code
#include "stdafx.h"#include <iostream>int _tmain(int argc, _TCHAR* argv[]){ int a = 0; int const &b = a; static_cast<int>(b) = 5; std::cout<<a<<std::endl; getchar(); return 0;}const的引用和对象本身却无关联。
- C/C++ code
#include "stdafx.h"#include <iostream>int _tmain(int argc, _TCHAR* argv[]){ double c = 5.0; int const &d = c; c = 6.0; std::cout << d <<std::endl; getchar(); return 0;}[解决办法]
int const &b = a;
static_cast<int>(b) = 5;
楼主却上上面这样写能通过编译码?
[解决办法]
static_cast<int>(b) = 5;
是个语法错误!
*const_cast<int*>(&b) = 6;
语法没错,有未定义行为!
const_cast<int&>(b) = 6;
同上!!!
[解决办法]
[解决办法]
1、static_cast<int>(b) = 5;
强制类型转换,关闭或挂起了正常的类型检查,从而改变了a的值。不建议这样使用。
2、int const &d = c;
c = 6.0;
std::cout << d <<std::endl;
对于上述代码编译器会进行这样的转换:
int temp = c;
const int &d = temp;
因为d是c的引用,所以c的值改变时,d的值也改变,
但是不能通过d去改变c的值,(例如:d = 8 错误!)因为d是const引用,是指向常对象。
const引用可以初始化为不同但相关的类型的对象或者初始化为右值
例如:
int a = 5;
double b = 5.5;
const int m = 5
const int &c = a; 或 const int &c = b; 或 const int &c = 33 或 const int &c = m;
