目录
练习6.16题解
局限性:由于该函数的形参是普通引用,所以该函数无法接收字符串常量以及字面值类型的实参,示例如下:
const string str;
bool flag = is_empty(str);//非法,普通的string& 不能绑定到string常量上
bool flag = is_empty("helloworld");//非法,普通的string& 不能绑定在字面值上
可以将函数的形参定义为常量引用加以改善,代码如下:
bool is_empty(const string &s){
return s.empty();
}
练习6.17题解
isUpper()函数和changeUpper()函数的形参类型不相同。因为changeUpper()函数的形参必须是普通引用,不能定义为常量引用,否则不能将s的大写字母修改为小写字母。代码如下:
#include <iostream>
using namespace std;
//1.编写函数:判断string对象是否含大写字母
bool isUpper(const string &s, int &occurs) {
//occurs要定义为引用类型,与实参绑定,才能在main()函数中输出n的值
occurs = 0; //记录s中大写字母的个数,初始为0
//使用范围for语句
for (auto c : s) {
if (isupper(c)) {
cout << c << " ";
occurs++;
}
}
cout << endl;
if (occurs > 0)
return true;
else
return false;
}
//编写函数:将string对象全部改写为小写形式
void changeUpper(string &s) {
//注意:变量c要定义成引用类型!!!
for (auto &c : s) {
c = tolower(c);
}
}
int main() {
//2.定义一个string对象
string s("HeLLo World");
int occurs = 0;
//3.调用isUpper()函数判断是否有大写字母
bool flag = isUpper(s, occurs);
cout << "s中是否含有大写字母? " << flag << endl;
cout << "s中大写字母的个数为:" << occurs << endl;
//4.调用changeUpper()函数将string对象全部改写为小写形式
changeUpper(s);
cout << s << endl;
return 0;
system("pause");
}
对于isUpper()函数,我多定义了一个形参,第二个形参occurs用以统计s中大写字母的个数。
这里我是用到了使用引用形参能够返回额外信息这一点,由于一个函数一次只能返回一个值,所以可以利用引用形参来返回多个结果。
练习6.18题解
bool compare(matrix &m1, matrix &m2);
vector<int>::iterator change_val(int, vector<int>::iterator);
练习6.19题解
(a.)不合法。cal中只有一个形参
(b.)合法。
(c.)合法。
(d.)合法。
练习6.20题解
- 当函数不改变形参的值时,就需要定义为常量引用。一般来说,应该尽量将引用形参设为常量引用。
- 如果形参应该是常量引用,而我们将其设为了普通引用,这会是一种错误,而且会误导调用者以为函数可以修改它的实参的值,并且极大地限制了函数所能接受的实参的类型,如不能把const对象、字面值或需要类型转换的对象传递给普通的引用形参。