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.
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.
相关文章推荐
- C++中Reference与指针(Pointer)的使用对比
- C++中Reference与指针(Pointer)的使用对比
- JsonHelper VS Newtonsoft.Json 不同情况的使用
- go语言方法Value Receiver, Pointer Receiver各种不同情况的实验笔记
- 同步和异步有何不同,在什么情况下分别使用他们?
- 使用python写一个监控不同机器的使用内存情况并使用flask出图
- 总结一下,以软件周期来说明不同的测试的使用情况
- 比较不同查询语句使用索引的情况
- 什么情况使用 weak 关键字,相比 assign 有什么不同?怎么用 copy 关键字?
- mapreduce输出时按情况使用不同的文件名输出结果
- 总结一下,以软件开发生命周期来说明不同测试使用的情况
- C++中Reference与指针(Pointer)的使用对比
- C++中Reference与指针(Pointer)的使用对比
- 以软件开发生命周期的过程来说明不同测试的使用情况
- QTcpSocket 对连接服务器中断的不同情况进行判定(六种情况,其中一种使用IsNetworkAlive API方法)
- CSS居中的不同情况使用不同的方法
- 安装Symbian的多个SDK,在多个SDK共存在情况下,要使用不同的SDK环境编译应用程序
- 在xml布局文件中,我们既可以设置px,也可以设置dp(或者dip)。一般情况下,我们都会选择使用dp,这样可以保证不同屏幕分辨率的机器上布局一致。但是在代码中,如何处理呢?很多控件的方法中都只提供了
- Delphi使用StrToDatetime在不同操作系统出现不同的情况
- RegisterType和RegisterInstance的不同使用情况--Unity Application Block(1)