您的位置:首页 > 其它

‘bout_"const char*& xx"

2012-02-16 16:35 525 查看
func(const char*& cp)


cp是指向“const char”的指针。cp他是引用。

----------------------------------------------------------------------------

const char* cp


cp是指向“const char”的指针。当然不是说cp必须只能指向const char,他也能指向char类型。

但意思是,cp可以修改自己的值从而指向不同地址,但是不能修改指向地址的存储的值。

即使是指向char类型的。

当你

char c = 'a';
const char* cp = &c;
*cp = ......;


上面编译就通不过。

------------------------------------------------------------------------------
下面是个比较全面的对比例子。

------------------------------------------------------------------------------

#include <iostream>
using namespace std;

char x = 'b';

void func(const char*& cp)
{
cp = &x;
}

void funcEX(const char* cp)
{
cp = &x;
}

//this function cannot compile successfully.
/*
void funcEX1(const char*& cp)
{
*cp = x;    //try to modify the value which cp points to.failure!
}*/

void main()
{
char b = 'a';    //
//const char b = 'a'; //is ok
const char* c = &b;
const char*& p = c;
cout<<"p:address:"<<(int)&p<<";"<<(int)p<<";value:"<<*p<<endl;
cout<<"c:address:"<<(int)&c<<";"<<(int)c<<";value:"<<*c<<endl;
cout<<"b:address:"<<(int)&b<<";value:"<<b<<endl;
cout<<"----------------------------------------------"<<endl;
funcEX(p);
cout<<"p:address:"<<(int)&p<<";"<<(int)p<<";value:"<<*p<<endl;
cout<<"c:address:"<<(int)&c<<";"<<(int)c<<";value:"<<*c<<endl;
cout<<"b:address:"<<(int)&b<<";value:"<<b<<endl;
cout<<"----------------------------------------------"<<endl;
func(p);
cout<<"p:address:"<<(int)&p<<";"<<(int)p<<";value:"<<*p<<endl;
cout<<"c:address:"<<(int)&c<<";"<<(int)c<<";value:"<<*c<<endl;
cout<<"b:address:"<<(int)&b<<";value:"<<b<<endl;
cout<<"----------------------------------------------"<<endl;
system("pause");
}


------------------------------------------------------------------

运行结果:



----------------------------------------------------------------

结果说明了引用的作用(funcEX()反向证明了),还有所谓的“改变自己指向的地址,而不能改变指向的地址存储的值”(注释里,funcEX1())。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: 
相关文章推荐