编写通常接受一个参数(字符串的地址),并打印该字符串的函数。然而,如果提供了第二个参数(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++;
}