标签:family str tor col style operator 存在 printf strong
我们知道在C++中引用和指针都可以用于间接访问指代对象,但是何时采用哪一个,也许我们并非很明确地知道。因此,写下本文为大家提供参考。
1、当可不指向任何对象,即NULL,使用指针
由于引用一定是指向某个对象的,不存在空引用。
2、当要求可指向另一对象时,使用指针
因引用总是指向最初获得的那个对象,不可更改
3、实现某些操作符时,如operator[],使用引用
4、因不存在空引用,引用更高效,不用判空
void printInt(const int& a) { printf("%d\r\n", a) } void printInt(const int* a) { if (a) { printf("%d\r\n", *a) } }
当一定指向某个对象,且不会更改指向的对象,则使用引用,否则使用指针。
标签:family str tor col style operator 存在 printf strong
原文地址:https://www.cnblogs.com/share-ideas/p/10664475.html