6.11
#include <iostream>
using namespace std;
void reset(int &i)
{
i = 0;
}
int main()
{
int j = 100000;
cout << "before reset: j = " << j << endl;
reset(j);
cout << "after reset: j = " << j << endl;
return 0;
}
6.12
#include <iostream>
using namespace std;
void swap(int &a, int &b)
{
int temp;
temp = a;
a = b;
b = temp;
}
int main()
{
int i = 10, j = 20;
//int &m = i, &n = j;
cout << "before swap: i = " << i << ", j = " << j << endl;
//swap(m, n);
swap(i, j);
cout << "after swap: i = " << i << ", j = " << j << endl;
return 0;
}
与使用指针相比,使用引用交换变量的内容从形式上看更简单一些,并且无需额外声明指针变量,也避免了拷贝指针的值。
6.13
void f(T)采用传值的方式,在函数f内部任何改动都不影响实参的值
void f(&T)采用传引用的方式,形参对应实参的别名,如果改变了形参的值,实参也会改变
#include <iostream>
using namespace std;
void f1(int a)
{
cout << "before: a = " << a << endl;
a++;
}
void f2(int &b)
{
cout << "before: b = "<< b << endl;
b++;
}
int main()
{
int a = 10;
int b = 10;
f1(a);
cout << "after: a = " << a << endl;
f2(b);
cout << "after: b = " << b << endl;
return 0;
}
6.14 略
6.15
a.对于字符串s,用引用避免字符串拷贝,用常量引用是因为无需改变字符串s的值
b.对于字符串c,占用一个字节,拷贝代价底,不需要用引用类型
c.对于occurs,因为需要隐式返回值,所以必须定义成引用类型,而且在函数内部有改变其值,所以不能用常量引用。
6.16
局限性:容易引起变量允许修改的误导,参数传递有限制,无法传递const对象、字面值常量和需要类型转换的对象
修改后
bool is_empty(const string &s) {return s.empty();}
6.17
#include <iostream>
#include <string>
#include <cctype>
using namespace std;
bool isUpper(const string &s)
{
for (auto it = s.begin(); it != s.end(); it++)
{
if ((*it) >= 'A' && (*it) <= 'Z')
{
cout << "has upper!!" << endl;
return true;
}
}
cout << "no upper!!" << endl;
return false;
}
bool isUpper2(const string &str)
{
for (auto c : str)
{
if (isupper(c))
{
return true;
}
}
return false;
}
void trans(string &s)
{
for (auto it = s.begin(); it != s.end(); it++)
{
if ((*it) >= 'A' && (*it) <= 'Z')
{
*it += 32;
}
cout << *it;
}
cout << endl;
}
void trans2(string &str)
{
for (auto &c : str)
{
c = tolower(c);
}
}
int main()
{
string str = "My Name Is Quan";
cout << isUpper(str) << endl;
trans(str);
string str2 = "My Love Is C";
cout << isUpper2(str2) << endl;
trans2(str2);
cout << str2 << endl;
//cout << trans2(str2) << endl;
return 0;
}
6.18
bool compare(const matrix &, const matrix &);
vector<int>::iterator change_val(int, vector<int>::iterator);
6.19
(a)非法,函数声明只有一个参数
(b)合法,字面值可以作为常量引用形参的值
(c)合法,整型会自动转换为double型
(d)合法的,前两个参数都是迭代器类型,3.8会自动转换为int类型
6.20 略