引用作为返回值的
来源:互联网 发布:福利直播软件 编辑:程序博客网 时间:2024/05/22 03:50
1. 返回引用的函数实际上是被引用的变量的别名
1,在作为函数参数和函数的返回值的引用
free_throws & accmulate(free_throws & target, const free_throws & source){ target.attempts += source.attempts; target.made += source.made; set_pc(target); return target;}
函数accmulate使用有好几种
- accmulate(team, one); display(team);
- display(accmulate(team, two));
- accmulate(accmulate(team, three), four);
- dup = accmulate(team, five);
- accmulate(dup, five) = team;
2,将const用于引用返回类型
const free_throws & accmulate(free_throws & target, const free_throws & source);
那么函数的一些的调用就不可以使用了
- accmulate(accmulate(team, three), four);
- accmulate(dup, five) = team;
3,将引用用于类对象
string version1(const string & s1, const string & s2){ string temp; temp = s2 + s1 + s2; return temp;}const string & version2(string & s1, const string & s2){ s1 = s2 + s1 + s2; return s1;}const string & version3(string & s1, const string & s2){ string temp; temp = s2 + s1 + s2; return temp; /*s1 = s2 + s1 + s2; return s1;*/}
测试test
void test01(){ string input; string copy; string result; cout << "Enter a string: "; getline(cin, input); copy = input; cout << "Your string as entered: " << input << endl; result = version1(input, "***"); cout << "Your string enhanced: " << result << endl; cout << "Your string enhanced: " << result << endl; cout << "Your original-string:" << input << endl; result = version2(input, "###"); cout << "Your string enhanced: " << result << endl; cout << "Your original string: " << input << endl; cout << "Resetting original string: \n"; input = copy; result = version3(input, "@@@"); //err cout << "Your string enhanced: " << result << endl; cout << "Your original string: " << input << endl;}
4,何时使用引用参数
使用引用参数的主要原因有两个
- 程序员能够修改调用函数中的数据对象。
- 通过传递引用而不是整个数据对象,可以提高程序的运行速度。
当数据对象较大时(如结构和类对象),第二个原因最重要。这些也是使用指针参数的原因。这是有道理的,因为引用参数实际上是基于指针的代码的另一个接口。那么,什么时候应使用引用,什么时候使用指针呢?什么时候应按值传递呢?下面是一些指导原则:
一,对于使用传递的值而不作修改的函数
- 如果数据对象很小,如内置数据类型或小型结构,可以按值传递。
- 如果数据对象是数组,值使用指针,因为这是唯一的选择,并将指针声明为指向const的指针。
- 如果数据对象是较大的结构,使用const指针或者const引用,以提高程序的效率。这样可以节省复制结构所需的时间和空间。
- 如果数据对象是类对象,使用const引用。类设计的语义常常要 求使用引用,这是C++新增这项的主要原因。因此,传递类对象参数的标准分数是按引用传递。
二,对于修改调用函数中数据的函数
- 如果数据对象是内置数据类型,则使用指针。如果看到诸如fixit(&x)这样的代码(其中x是int),则很明显,该函数将修改x。
- 如果数据对象是数组,则只能使用指针。
- 如果数据对象是结构,则使用引用或指针。
- 如果数据对象是类对象,则使用引用。
阅读全文
0 0
- 引用作为返回值的
- 引用作为返回值
- 引用作为返回值
- 引用作为函数返回值的情况
- 引用作为返回值的注意事项
- 引用作为函数返回值
- 引用作为函数返回值
- 引用作为函数返回值
- 引用作为函数返回值
- 引用作为函数返回值
- 引用作为函数返回值
- C++引用作为返回值
- 引用作为函数返回值
- 引用作为函数返回值
- 引用作为函数返回值
- 引用作为函数返回值
- C++:引用作为返回值
- 引用作为函数返回值
- 162. Find Peak Element
- @RequiresPermissions 控制权限的异常处理以及Ajax方式请求时返回json
- 不规则卷积神经网络
- 插入、冒泡、归并、堆排序、快排总结
- Java学习线路
- 引用作为返回值的
- 关于EOS的部署
- opencv 实现任意角度的透视变换
- SVN的安装和关联Android Studio的重要步骤
- 安卓发布应用、更新的细节
- IPython notebook的安装及安装后网页不能打开问题
- python基础教程——dict和se
- Hadoop mapreduce 入门示例详解
- 数据结构中的单链表的相关处理