您的位置:首页 > 其它

引用作为返回值的

2017-09-13 12:45 225 查看
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。

如果数据对象是数组,则只能使用指针。

如果数据对象是结构,则使用引用或指针。

如果数据对象是类对象,则使用引用。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: