C++ Primer第五版_第六章习题答案(41~50)

练习6.41

下面的哪个调用是非法的?为什么?哪个调用虽然合法但显然与程序员的初衷不符?为什么?

char *init(int ht, int wd = 80, char bckgrnd = ' ');
(a) init();
(b) init(24,10);
(c) init(14,'*');
  • (a) 非法。第一个参数不是默认参数,最少需要一个实参。
  • (b) 合法。
  • © 合法,但与初衷不符。字符 * 被解释成 int 传入到了第二个参数。而初衷是要传给第三个参数。

练习6.42

给make_plural函数的第二个形参赋予默认实参’s’, 利用新版本的函数输出单词success和failure的单数和复数形式。

#include <iostream>
#include <string>

using std::string;
using std::cout;
using std::endl;

string make_plural(size_t ctr, const string& word, const string& ending = "s")
{
	return (ctr > 1) ? word + ending : word;
}

int main()
{
	cout << "singual: " << make_plural(1, "success", "es") << " "
		<< make_plural(1, "failure") << endl;
	cout << "plural : " << make_plural(2, "success", "es") << " "
		<< make_plural(2, "failure") << endl;

	return 0;
}

练习6.43

你会把下面的哪个声明和定义放在头文件中?哪个放在源文件中?为什么?

(a) inline bool eq(const BigInt&, const BigInt&) {...}
(b) void putValues(int *arr, int size);

全部都放进头文件。(a) 是内联函数,(b) 是声明。

练习6.44

将6.2.2节的isShorter函数改写成内联函数。

inline bool is_shorter(const string &lft, const string &rht) 
{
    return lft.size() < rht.size();
}

练习6.45

回顾在前面的练习中你编写的那些函数,它们应该是内联函数吗?如果是,将它们改写成内联函数;如果不是,说明原因。

一般来说,内联机制用于优化规模小、流程直接、频繁调用的函数。

练习6.46

能把isShorter函数定义成constexpr函数吗?如果能,将它改写成constxpre函数;如果不能,说明原因。

不能。constexpr函数的返回值类型及所有形参都得是字面值类型。

扫描二维码关注公众号,回复: 14571444 查看本文章

练习6.47

改写6.3.2节练习中使用递归输出vector内容的程序,使其有条件地输出与执行过程有关的信息。例如,每次调用时输出vector对象的大小。分别在打开和关闭调试器的情况下编译并执行这个程序。

#include <iostream>
#include <vector>

using namespace std;

using Iter = vector<int>::const_iterator;

#define NDEBUG

void print(Iter first, Iter last)
{
#ifndef NDEBUG
	cout << "vector size: " << last - first << endl;
#endif
	if (first == last)
	{
		cout << "over!" << endl;
		return;
	}
	cout << *first << " ";
	print(++first, last);

}

int main()
{
	vector<int> vec{ 1, 2, 3, 4, 5, 6, 7, 8, 9 };
	print(vec.cbegin(), vec.cend());

	return 0;
}

练习6.48

说明下面这个循环的含义,它对assert的使用合理吗?

string s;
while (cin >> s && s != sought) { } //空函数体
assert(cin);

不合理。从这个程序的意图来看,应该用

assert(s == sought);

练习6.49

什么是候选函数?什么是可行函数?

  • 候选函数:与被调用函数同名,并且其声明在调用点可见。
  • 可行函数:形参与实参的数量相等,并且每个实参类型与对应的形参类型相同或者能转换成形参的类型。

练习6.50

已知有第217页对函数 f 的声明,对于下面的每一个调用列出可行函数。其中哪个函数是最佳匹配?如果调用不合法,是因为没有可匹配的函数还是因为调用具有二义性?

(a) f(2.56, 42)
(b) f(42)
(c) f(42, 0)
(d) f(2.56, 3.14)
  • (a) void f(int, int);void f(double, double = 3.14); 是可行函数。该调用具有二义性而不合法。
  • (b) void f(int); 是可行函数。调用合法。
  • © void f(int, int);void f(double, double = 3.14); 是可行函数。void f(int, int); 是最佳匹配。
  • (d) void f(int, int);void f(double, double = 3.14); 是可行函数。void f(double, double = 3.14); 是最佳匹配。

猜你喜欢

转载自blog.csdn.net/lxy_2011/article/details/129785178
今日推荐