C++基础学习(三)之函数

函数的基本结构

Return_type Function_name(parameter list)
{
    body of the function
}

函数声明

#include<iostream>
void main()
{
    void function(int a, int b);  //函数声明1
    //void function(int, int);  //函数声明2
    ...
    int x = 15, y = 20;
    function(x, y);  //函数调用,x、y为实参(实际参数)
}
void function(int a, int b)  //a、b为形参(形式参数)
{
    ...
}

多文件(.cpp)之间的函数调用

1 利用函数声明

在主文件中直接进行声明即可,无需添加“function.cpp”源文件,否则报错;

//function.cpp
#include<iostream> void function() { ... }
//main.cpp
#include<iostream>
void function();  //函数声明
void main()
{
    ...
    function();  //函数调用
    ...
}

2 利用头文件

在主文件中添加头文件“function.h”即可,无需声明函数;

//function.h
#include<iostream>
void function();
//function.cpp
#include"function.h"
void function()
{
    ...
}
//main.cpp
#include<iostream>
#include"function.h"
void main()
{
    ...
    function();  //函数调用
    ...
}

函数参数传递

0 传值调用

值传递,形参不影响实参;

1 指针调用

#include<iostream>
using namespace std;
void swap(int *x, int *y) //参数互换 { int temp; temp = x; x = y; y = temp; } int main() { int a = 10, b = 20; cout << a << endl << b << endl; swap(&a, &b); cout << a << endl << b << endl; return 0; }

2 引用调用

#include<iostream>
using namespace std;
void swap(int &x, int &y) //参数互换 { int temp; temp = x; x = y; y = temp; } int main() { int a = 10, b = 20; cout << a << endl << b << endl; swap(a, b); cout << a << endl << b << endl; return 0; }

默认参数

#include<iostream>

int function(int a, int b = 10)  //形参b赋予默认值10,如果函数调用过程中实参为空,则使用默认参数10
{
    ...
}
int main() { ... function(x, y); function(x, ); ... }
原文地址:https://www.cnblogs.com/haijian/p/13062587.html