练习6.1
实参和形参的区别的什么?
形参在函数的定义中声明;
实参是形参的初始值。
练习6.2
请指出下列函数哪个有错误,为什么?应该如何修改这些错误呢?
(a) int f() {
string s;
// ...
return s;
}
(b) f2(int i) {
/* ... */ }
(c) int calc(int v1, int v1) {
/* ... */ }
(d) double square (double x) return x * x;
(a)返回类型为int,但是实际返回了字符串:
string f() {
// return should be string, not int
string s;
// ...
return s;
}
(b)需要加上函数声明:
void f2(int i) {
/* ... */ } // function needs return type
(c)形参的名字不能相同:
int calc(int v1, int v2) {
/* ... */ } // parameter list cannot use same name twice
(d)需要有大括号(块):
double square (double x) {
return x * x; } // function body needs braces
练习6.3
编写你自己的fact函数,上机检查是否正确。
#include <iostream>
int fact(int n)
{
int ret = 1;
for(int i = 1;i <= n;++i)
{
ret *= i;
}
return ret;
}
int main()
{
std::cout << fact(5) << std::endl;
return 0;
}
练习6.4
编写一个与用户交互的函数,要求用户输入一个数字,计算生成该数字的阶乘。在main函数中调用该函数。
#include <iostream>
int fact(int n)
{
int ret = 1;
for(int i = 1;i <= n;++i)
{
ret *= i;
}
return ret;
}
int main()
{
int n;
std::cin >> n;
std::cout << fact(n) << std::endl;
return 0;
}
练习6.5
编写一个函数输出其实参的绝对值。
#include <iostream>
int absolute(int n)
{
return (n > 0) ? n : -n;
}
int main()
{
std::cout << absolute(5) << std::endl;
return 0;
}
练习6.6
说明形参、局部变量以及局部静态变量的区别。编写一个函数,同时达到这三种形式。
形参是局部变量的一种。
形参和函数体内部定义的变量统称为局部变量。
局部静态变量的生命周期贯穿函数调用及之后的时间。
// example
size_t count_add(int n) // n is a parameter and local variable.
{
static size_t ctr = 0; // ctr is a static variable.
ctr += n;
return ctr;
}
int main()
{
for (size_t i = 0; i != 10; ++i) // i is a local variable.
cout << count_add(i) << endl;
return 0;
}
练习6.7
编写一个函数,当它第一次被调用时返回0,以后每次被调用返回值加1。
size_t generate()
{
static size_t ctr = 0;
return ctr++;
}
练习6.8
编写一个名为Chapter6.h 的头文件,令其包含6.1节练习中的函数声明。
#ifndef CHAPTER6_H
#define CHAPTER6_H
int fact(int n);
int absolute(int n);
#endif
练习6.9
编写你自己的fact.cc 和factMain.cc ,这两个文件都应该包含上一小节的练习中编写的 Chapter6.h 头文件。通过这些文件,理解你的编译器是如何支持分离式编译的。
fact.cpp
#include "Chapter6.h"
int fact(int n)
{
int ret = 1;
for(int i = 1;i <= n;++i)
{
ret *= i;
}
return ret;
}
int absolute(int n)
{
return (n > 0) ? n : -n;
}
factMain.cpp
#include <iostream>
#include "Chapter6.h"
int main()
{
std::cout << fact(5) << std::endl;
return 0;
}
$ g++ -o ex09 factMain.cpp fact.cpp -std=c++11
$ ./ex09
120
练习6.10
编写一个函数,使用指针形参交换两个整数的值。在代码中调用该函数并输出交换后的结果,以此验证函数的正确性。
#include <iostream>
void swap_int(int *i,int *j)
{
int tmp = *i;
*i = *j;
*j = tmp;
}
int main()
{
int i = 1,j = 2;
std::cout << i << " " << j << std::endl;
swap_int(&i,&j);
std::cout << i << " " << j << std::endl;
return 0;
}
练习6.11
编写并验证你自己的reset函数,使其作用于引用类型的参数。
#include <iostream>
void reset(int &i)
{
i = 0;
}
int main(int argc, char const *argv[])
{
int i = 100;
std::cout << i << std::endl;
reset(i);
std::cout << i << std::endl;
return 0