指针和应用的区别
(1)非空区别。在任何情况下都不能使用指向空值的引用。一个引用必须总是指向某些对象。因此如果你使用一个变量并让他指向一个对象,但是该变量在某些时候也可能不指向任何对象,这是你应该把变量声明为指针,因为这样你可以赋予空值给该变量。相反,如果变量肯定指向一个对象,例如你的设计不允许变量为空,这时你就可以把变量声明为引用。不存在指向空值得引用这个事实意味着使用引用的代码效率比使用指针要高。
(2)合法性区别。在使用引用之前不需要测试它的合法性。相反,指针则应该总是被测试,防止其为空。
(3)可修改区别。指针与引用的另一个重要的不同是指针可以被重新赋值以指向另一个不同的对象。但是引用则是总是指向在初始化时被指定的对象,以后不能改变,但是指定的对象其内容可以改变。
(4)应用区别。总的来说,在以下情况下你应该使用指针:一是你考虑到存在不指向任何对象对象的可能(在这种情况下,你能够设置指针为空),二是你需要能够在不同的时刻指向不同的对象(在这种情况下,你能改变指针的指向)。如果总是指向一个对象并且一旦指向一个对象后就不会改变指向,那么你应该使用引用。
文章出处:http://www.diybl.com/course/3_program/c++/cppxl/20081125/152591.html
参考以下代码理解上面区别:
- #include <iostream>
- using namespace std;
- int main(int argc, char* argv[])
- {
- int ival = 1024;
- int *pi = &ival; // a pointer
- int &rval = ival; // a reference
- int jval = 4096;
- int xval = 8192;
- cout << "ival = " << ival << "/t";
- cout << "&ival = " << &ival << "/t";
- cout << endl;
- cout << "pi = " << pi << "/t";
- cout << "&pi = " << &pi << "/t";
- cout << "*pi = " << *pi << "/t";
- cout << endl;
- cout << "rval = " << rval << "/t";
- cout << "&rval = " << &rval << "/t";
- cout << endl;
- cout << "jval = " << jval << "/t";
- cout << "&jval = " << &jval << "/t";
- cout << endl;
- // change the values of the reference and the pointer
- pi = &jval;
- rval = jval;
- // print the changes
- cout << endl;
- cout << "ival = " << ival << "/t";
- cout << "&ival = " << &ival << "/t";
- cout << endl;
- cout << "pi = " << pi << "/t";
- cout << "&pi = " << &pi << "/t";
- cout << "*pi = " << *pi << "/t";
- cout << endl;
- cout << "rval = " << rval << "/t";
- cout << "&rval = " << &rval << "/t";
- cout << endl;
- cout << "jval = " << jval << "/t";
- cout << "&jval = " << &jval << "/t";
- cout << endl;
- cout << endl;
- *pi = xval;
- cout << "pi = " << pi << "/t";
- cout << "&pi = " << &pi << "/t";
- cout << "*pi = " << *pi << "/t";
- cout << endl;
- cout << "jval = " << jval << "/t";
- cout << "&jval = " << &jval << "/t";
- cout << endl;
- return 0;
- }