一 按地址传递参数的函数
1 代码
#include <iostream>
using namespace std;
void duplicate(int& a, int& b, int &c)
{
a *= 2;
b *= 2;
c *= 2;
}
int main()
{
int x = 1, y = 3, z = 7;
duplicate(x, y, z);
cout << "x=" << x << ", y=" << y << ", z=" << z<<endl;
return 0;
}
2 编译运行
[root@localhost test]# g++ test.cpp -o test
[root@localhost test]# ./test
x=2, y=6, z=14
3 说明
当按地址传递一个变量的时候,是在传递这个变量本身,在函数中对变量所做的任何修改都会影响函数外面被传递的变量。
二 按地址传递使函数返回多个值
1 代码
#include <iostream>
using namespace std;
void prevnext(int x, int& prev, int& next)
{
prev = x - 1;
next = x + 1;
}
int main()
{
int x = 100, y, z;
prevnext(x, y, z);
cout << "Previous=" << y << ", Next=" << z<<endl;
return 0;
}
2 编译运行
[root@localhost test]# g++ test.cpp -o test
[root@localhost test]# ./test
Previous=99, Next=101
三 函数的默认值
1 代码
#include <iostream>
using namespace std;
int divide(int x, int y=2)
{
int r;
r=x/y;
return r;
}
int main()
{
cout << divide(12);
cout << endl;
cout << divide(20,4);
return 0;
}
2 运行
[root@localhost test]# g++ test1.cpp -o test1
[root@localhost test]# ./test1
6
5
3 说明
当调用函数时,没有给出第2个参数,将使用默认值进行调用。
四 函数重载
1 代码
#include <iostream>
using namespace std;
int divide(int a, int b) {
return (a / b);
}
float divide(float a, float b) {
return (a / b);
}
int main() {
int x = 5, y = 2;
float n = 5.0, m = 2.0;
cout << divide(x, y);
cout << "\n";
cout << divide(n, m);
cout << "\n";
return 0;
}
2 运行
[root@localhost test]# g++ test.cpp -o test
[root@localhost test]# ./test
2
2.5
3 说明
编译器通过检查传入的参数类型来确定是哪一个函数被调用。
五 函数的声明
1 代码
#include <iostream>
using namespace std;
void odd(int a); // 函数声明放在头部
void even(int a); // 函数声明放在头部
int main() {
int i;
do {
cout << "Type a number: (0 to exit)";
cin >> i;
odd(i);
} while (i != 0);
return 0;
}
void odd(int a) {
if ((a % 2) != 0) cout << "Number is odd.\n";
else even(a);
}
void even(int a) {
if ((a % 2) == 0) cout << "Number is even.\n";
else odd(a);
}
2 运行
[root@localhost test]# g++ test.cpp -o test
[root@localhost test]# ./test
Type a number: (0 to exit)5
Number is odd.
Type a number: (0 to exit)6
Number is even.
Type a number: (0 to exit)0
Number is even.
3 说明
函数声明可以让函数在被完整定义之前就被使用。如果不使用函数声明,就限制了函数在源文件中的位置。