《C++ Primer》5th 课后练习 第六章 函数 51~56

练习 6.51 编写函数f的4版本,令其各输出一条可以区分的消息。验证上一个练习的答案,如果你的回答错了,反复研究本节内容直到你弄清自己错在何处。

#include<iostream>
#include<string>
#include<vector>
using namespace std;
void f() {
	cout << "i'm f()" << endl;
}
void f(int a) {
	cout << "i'm f(int)" << endl;
}
void f(int a, int b) {
	cout << "i'm f(int, int)" << endl;
}
void f(double a, double b = 3.14) {
	cout << "i'm f(double, double)" << endl;
}
int main(int argc, char **argv)
{
	//f(2.56, 42);
	f(42);
	f(42, 0);
	f(2.56, 3.14);
}

练习 6.52 已知有如下声明:

void manip(int ,int);
double dobj;

请指出下列调用中每个类型转换的等级。

(a) manip('a', 'z');
(b) manip(55.4, dobj);
  • a) 类型提升转换,等级3
  • b) 算术提升转换,等级4

练习 6.53 说明下列每组声明中的第二条语句会产生什么影响,并指出哪些不合法(如果有的话)。

(a) int calc(int&, int&); 
	int calc(const int&, const int&); 
(b) int calc(char*, char*);
	int calc(const char*, const char*);
(c) int calc(char*, char*);
	int calc(char* const, char* const);
  • a) 合法,重载了calc函数
  • b) 合法,重载了calc函数
  • c) 不合法, 顶层const不影响传入函数的对象。

练习 6.54 编写函数的声明,令其接受两个int形参并返回类型也是int;然后声明一个vector对象,令其元素是指向该函数的指针。

int func(int a, int b);
vector<decltype(func)*> vec;

练习 6.55 编写4个函数,分别对两个int值执行加、减、乘、除运算;在上一题创建的vector对象中保存指向这些函数的指针。

#include<iostream>
#include<string>
#include<vector>
using namespace std;
int func(int a, int b);
inline int add(int a, int b) {
	return a + b;
}
inline int subtract(int a, int b) {
	return a - b;
}
inline int multiply(int a, int b) {
	return a * b;
}
inline int divide(int a, int b) {
	return a / b;
}

int main(int argc, char **argv)
{
	vector<decltype(func) *> vec;
	vec.push_back(add);
	vec.push_back(subtract);
	vec.push_back(multiply);
	vec.push_back(divide);
	return 0;
}

练习 6.56 调用上述vector对象中的每个元素并输出结果。

#include<iostream>
#include<string>
#include<vector>
using namespace std;
int func(int a, int b);
inline int add(int a, int b) {
	return a + b;
}
inline int subtract(int a, int b) {
	return a - b;
}
inline int multiply(int a, int b) {
	return a * b;
}
inline int divide(int a, int b) {
	return a / b;
}

int main(int argc, char **argv)
{
	vector<decltype(func) *> vec;
	vec.push_back(add);
	vec.push_back(subtract);
	vec.push_back(multiply);
	vec.push_back(divide);
	int x = 6, y = 3;
	int num = -1;
	for (auto &oper : vec) {
		cout << "oper " << ++num << ": " <<oper(x, y) << endl;
	}
	return 0;
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值