46-复习题
18.11 复习题
1.使用用大括号括起的初始化列表语法重写下述代码。重写后的代码不应使用数组ar:
class Z200
{
private:
int j;
char ch;
double z;
public:
Z200(int jv, char chv, zv) : j(jv), ch(chv), z(zv) {}
...
};
double x = 8.8;
std::string s = "What a bracing effect!";
int k(99);
Z200 zip(200,'Z',0.675);
std::vector<int> ai(5);
int ar[5] = {3, 9, 4, 7, 1};
for (auto pt = ai.begin(), int i = 0; pt != ai.end(); ++pt, ++i)
*pt = ai[i];
2.在下述简短的程序中,哪些函数调用不对?为什么?对于合法的函数调用,指出其引用参数指向的是什么。
#include <iostream>
using namespace std;
double up(double x) { return 2.0* x;}
void r1(const double &rx) {cout << rx << endl;}
void r2(double &rx) {cout << rx << endl;}
void r3(double &&rx) {cout << rx << endl;}
int main()
{
double w = 10.0;
r1(w);
r1(w+1);
r1(up(w));
r2(w);
r2(w+1);
r2(up(w));
r3(w);
r3(w+1);
r3(up(w));
return 0;
}
3.a.下述简短的程序显示什么?为什么?
#include <iostream>
using namespace std;
double up(double x) { return 2.0* x;}
void r1(const double &rx) {cout << “const double & rx\n”;}
void r1(double &rx) {cout << “double & rx\n”;}
int main()
{
double w = 10.0;
r1(w);
r1(w+1);
r1(up(w));
return 0;
}
b.下述简短的程序显示什么?为什么?
#include <iostream>
using namespace std;
double up(double x) { return 2.0* x;}
void r1(double &rx) {cout << “double & rx\n”;}
void r1(double &&rx) {cout << “double && rx\n”;}
int main()
{
double w = 10.0;
r1(w);
r1(w+1);
r1(up(w));
return 0;
}
c.下述简短的程序显示什么?为什么?
#include <iostream>
using namespace std;
double up(double x) {return 2.0* x;}
void r1(const double &rx) {cout << “const double & rx\n”;}
void r1(double &&rx) {cout << “double && rx\n”;}
int main()
{
double w = 10.0;
r1(w);
r1(w+1);
r1(up(w));
return 0;
}
4.哪些成员函数是特殊的成员函数?它们特殊的原因是什么?
5.假设Fizzle类只有如下所示的数据成员:
class Fizzle
{
private:
double bubbles[4000];
...
};
为什么不适合给这个类定义移动构造函数?要让这个类适合定义移动构造函数,应如何修改存储4000个double值的方式?
6.修改下述简短的程序,使其使用lambda表达式而不是f1()。请不要修改show2()。
#include <iostream>
template<typename T>
void show2(double x, T& fp) {std::cout << x << " -> " << fp(x) << '\n';}
double f1(double x) { return 1.8*x + 32;}
int main()
{
show2(18.0, f1);
return 0;
}
7.修改下述简短而丑陋的程序,使其使用lambda表达式而不是函数符Adder。请不要修改sum()。
#include <iostream>
#include <array>
const int Size = 5;
template<typename T>
void sum(std::array<double,Size> a, T& fp);
class Adder
{
double tot;
public:
Adder(double q = 0) : tot(q) {}
void operator()(double w) { tot +=w;}
double tot_v () const {return tot;};
};
int main()
{
double total = 0.0;
Adder ad(total);
std::array<double, Size> temp_c = {32.1, 34.3, 37.8, 35.2, 34.7};
sum(temp_c,ad);
total = ad.tot_v();
std::cout << "total: " << ad.tot_v() << '\n';
return 0;
}
template<typename T>
void sum(std::array<double,Size> a, T& fp)
{
for(auto pt = a.begin(); pt != a.end(); ++pt)
{
fp(*pt);
}
}