c++里引用有啥意义

没有引用,你打算怎么写操作符重载?---Bjarne Stroustrup 爷爷在《The Design and Evolution of C++》第 3.7 节中写道:References were introduced primarily to support operator overloading.歌词大意:「之所以加入引用,主要是为了支持操作符重载。」---a = b + c; // 日常写法Widget operator+(Widget const\u0026amp; lhs, Widget const\u0026amp; rhs){ // blah blah blah}没有引用,只用指针你写不出来呀,总不见得你要别人写这样的吧:a = \u0026amp;b + \u0026amp;c; // 日常写法Widget operator+(Widget const *lhs, Widget const *rhs){ // blah blah blah}
■网友
引用可以替代一部分指针的功能。比方说有这么两个变量:int a = 1;int b = 2;现在我要你写个函数交换这两个变量的值。用指针怎么写?——默认你知道写成 void swap (int a, int b) { ... } 是不对的。void swap(int *p1, int *p2){\tint temp = *p1;\t*p1 = *p2;\t*p2 = temp;}这怎么调用?swap(\u0026amp;a, \u0026amp;b);cout \u0026lt;\u0026lt; a \u0026lt;\u0026lt; ", " \u0026lt;\u0026lt; b \u0026lt;\u0026lt; endl;输出结果会是:2, 1用引用怎么写?void swap(int \u0026amp;a, int \u0026amp;b){\tint temp = a;\ta = b;\tb = temp;}怎么调用?swap(a, b);cout \u0026lt;\u0026lt; a \u0026lt;\u0026lt; ", " \u0026lt;\u0026lt; b \u0026lt;\u0026lt; endl;结果一样是成功交换:2, 1=======================================没有引用当然还是可以写重载的:class Vector3{\tfloat v;public:\t...\t...}Vector3 operator+(Vector3 a, Vector3 b){\treturn Vector3(a.getX() + b.getX(), a.getY() + b.getY(), a.getZ() + b.getZ());}只不过这样子传参数是值传递、拷贝数据。也容易踩坑。用引用的话,实际只是传了地址,性能会好些:
■网友
more effective c++ 第一条就是


    推荐阅读