C++编程实践 : 默认参数 (习题引自C++ Primer Plus)

编写通常接受一个参数(字符串的地址),并打印该字符串的函数。然而,如果提供了第二个参数(int类型),且该参数不为0,则该函数打印字符串的次数将为该函数被调用的次数(注意,字符串的打印次数不等于第二个参数的值,而等于函数被调用的次数)。是的,这是一个非常可笑的函数,但它让您能够使用本章介绍的一些技术。在一个简单的程序中使用该函数,以演示该函数是如何工作的。

这里面含有以下几个知识点:
a 默认参数的设置
b 含有默认参数的函数的定义
c 静态变量的运用

实践:

#include <iostream>
#include <string>
using namespace std;
void printctr(const string &s, int n = 0);
// 默认参数: 从右向左设置,从左向右调用。

int main() {
	string name;
	name = "banana";
	printctr(name, 4);
	printctr(name, 4);
	printctr(name, 4);
	printctr(name, 4);
	printctr(name, 4);
	return 0;
}

// !!! 默认参数的函数声明和定义是有区别的:
// !!! 声明有默认参数的数值,定义没有默认参数的数值。
/*
报错信息:
[Error] default argument given for parameter 2 of 'void printctr(const string&, int)' [-fpermissive]
[Note] previous specification in 'void printctr(const string&, int)' here
*/ 
void printctr(const string &s, int n) {
	static int ctr = 0;  // 静态变量
	if (n != 0) {
		for (int i = 0; i < ctr; i++)
			cout << s << endl; 
	}
	cout << "cout : " << ctr+1 << " cout !" << endl;
	ctr++;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值