1.参数传递
- 参数传递:pass by value vs. pass by reference(to const)
- 推荐:能传引用,尽量传引用(高效,尤其在需要拷贝的对象很大时)
class complex { public: complex(double r = 0, double i = 0) : re (r), im (i) {} complex& operator += (const complex&); double real() const { return re; } double imag() const { return im; } private: double re; double im; friend complex& __doapl(complex*, const complex&); };
ostream& operator << (ostream& os, const complex& x)
//注意:const能加则加,会形成良好的区分,传递更多隐含信息 比如这里可以读出:os的值会改变,而x的不会变 { return os << '(' << real(x) << ',' << imag(x) << ')'; }
2.返回值传递
- 返回值传递:return by value vs. return by reference(to const)
- 推荐:能传引用,尽量传引用(高效,尤其在需要拷贝的对象很大时)
class complex { public: complex(double r = 0, double i = 0) : re (r), im (i) {} complex& operator += (const complex&); double real() const { return re; } double imag() const { return im; } private: double re; double im; friend complex& __doapl(complex*, const complex&); };
3.引用的简介
- 引用,即别名,是变量的别名;
- 传引用,即通过别名直接访问变量,使用引用比指针更安全也更漂亮;
- 引用的实质:引用在底层实际为指针(一般为4个byte的地址)。
4.不能传引用的情况
//可以传引用 int c1, c2; int& add(int c1,int c2) { c1 += c2; //c1已存在,且add执行完毕后仍然有效 } //不能传引用 int add(int c1, int c2) { int c3 = c1 + c2; //c3为新创建的局部变量,add执行完毕后失效 }
- (1)当对象尚不存在时,不能传引用(根本的原则);
- (2)对象为局部变量,函数执行完毕后即失效,不能传引用,因为对象消失了,引用自然失效。
参考资料:
1.www.geekband.com 侯捷——C++基础课视频,来源B站