const指针的引用
下面是关于const指针的引用测试(vs2005):
1)对于非指针引用的形参,如fun1,传入非const实参没问题,如fun1(a)
但对于指针引用的形参,如fun,传入非const实参却有问题,如fun(b),
而传入const实参就没有问题,如fun(c),
为什么?
2)另外,进行强制类型转换,将非const实参转换为const实参,
这种转换(const int *)是错误的,如fun((const int *)d),
而必须这样转换fun((const int *&)e),
为什么?
#include "stdafx.h"
void fun(const int *&)
{
}
void fun1(const int &)
{
}
int _tmain(int argc, _TCHAR* argv[])
{
int a = 0;
fun1(a);//ok
int *b = new int(0);
fun(b);//error
delete b;
const int *c = new int(0);
fun(c);//ok
delete c;
int *d = new int(0);
fun((const int *)d);//error
delete d;
int *e = new int(0);
fun((const int *&)e);//ok
delete e;
return 0;
}