1、函数的定义
步骤:
返回值类型 函数名(参数表)
{
函数体语句;
return表达式;
}
应用案例:实现一个加法功能,要求传入两个整型数据,计算数据相加的结果,并且输出。
`int add(int num1, int num2)`
`{`
`int sum;`
`sum = num1 + num2;`
`return 0;`
`}`
2、函数的调用
`#include<iostream>`
`using namespace std;`
`int add(int num1, int num2) //在函数定义的过程中,num1和num2并没有实际的数值,只是一个形式参数,简称形参`
`{`
`int sum;`
`sum = num1 + num2;`
`return sum;`
`}`
`int main()`
`{`
`int a = 100;`
`int b = 200;`
`int c = add(a,b); //a和b在实际传递过程中,有一个实际的参数,称为实参`
`cout << "c=" << c << endl;`
`system("pause");`
`return 0;`
`}`
函数定义里小括号内称为形参,函数调用时传入的参数成为实参。
3、值传递
即函数调用时,实参将数值传递给形参;(当形参发生变化时,实参不会发生变化)
`#include<iostream>`
`using namespace std;`
`void swap(int num1, int num2)`
`{`
`cout << "交换前" << endl;`
`cout << "num1=" << num1 << endl;`
`cout << "num2=" << num2 << endl;`
`int temp=0;`
`num1 = num2;`
`num2 = temp;`
`cout << "交换后" << endl;`
`cout << "num1=" << num1 << endl;`
`cout << "num2=" << num2 << endl;`
`}`
`int main()`
`{`
`int a = 10;`
``int b = 20; swap(a, b);`
`cout <<"a="<< a << endl;`
`cout <<"b="<< b << endl;`
`system("pause");`
`return 0;`
`}`
值传递过程中,形参发生任何变化都不会使实参变化,
4、函数常见样式
有参有返 无参无返 有参无返 无参有返
`void test01()//无参无返`
`{`
`cout << "this is test01" << endl;`
`}`
`void test02(int a)//有参无返`
`{`
`cout << "this is test02" << endl;`
`}`
`int test03()//无参有返`
`{`
`cout << " " << endl;`
`return 1000;`
`}`
`int test04(int a)//有参有返`
`{`
`cout << a << endl;`
`return a;`
`}`
`int main() {`
`test01();//无参无返的调用`
`test02(100);//有参无返的调用`
`int num1=test03();//无参有返的调用`
`cout << "num1=" << num1 << endl;//无参有返的调用`
`int num2=test04(10000);//有参有返的调用`
`cout << "num2=" << num2 << endl;//有参有返的调用`
``
`}`
5、函数的声明
如果函数定义在主函数之前,不一定需要函数声明;当函数定义在主函数之后的时候,则一定需要函数声明。
函数声明可以出现多次,但是函数定义只能有一次。
6、指针
定义指针语法:数据类型*指针变量名;
指针其实就是变量的地址
`int main() {`
`int a = 2;`
`int *p;//定义指针`
`p = &a;`
`cout << "a的地址为:" << &a << endl;`
`cout << "指针p为:" << p << endl;`
//使用指针
//可以通过解引用的方式来找到指针指向的内存
//指针前加*代表解引用,找到指针指向的内存中的数据
*p = 1000;
cout << "a=" << a << endl;
cout << "*p=" << *p << endl;
system("pause");
return 0;}