您的位置:首页 > Web前端

pointer 和 reference的不同使用情况

2009-02-12 02:35 169 查看
读more effective c++ 注意到一个以前没有注意的细节问题:

pointer 和 reference 都是地址形式,他们在使用上有什么区别呢?

下面的例子很好的说明了两者的区别:

reference:

void printDouble(const double &rd){

cout<<rd; //no need to test rd, it must refer to a double

}

pointer:

void printDouble(const double *pd){

if(pd){

cout<< *pd; // need to check for null pointer problem

}

}

另一个重要的区别是 pointer 可以重新指向不同的对象, 而reference永远指向它初始化时候的对象。

string s1("Nancy");

string s2(“Clancy”);

string &rs = s1;

string *ps = &s1;

rs = s2; //rs still refers to s1, but the content in s1 is changed to Clancy

ps = &s2; // ps now point to s2, but s1 is unchanged.
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: 
相关文章推荐