1、函数定义
#include <iostream> using namespace std; int add(int num1, int num2) { int sum = num1 + num2; return sum; } int main() { system("pause"); return 0; }
2、函数的调用
#include <iostream> using namespace std; int add(int num1, int num2) { int sum = num1 + num2; return sum; } int main() { int a = 10; int b = 20; int sum = add(a, b); cout << sum << 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 = num1; 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、函数的常见样式
#include <iostream> using namespace std; //1、无参无返 void test01() { cout << "this is test01" << endl; } //2、有参无返 void test02(int a) { cout << "this is test02 a = " << a << endl; } //3、无参有返 int test03() { cout << "this is test03" << endl; return 1000; } //4、有参有返 int test04(int a) { cout << "this is test04 a = " << a << endl; return a; } int main() { //无参无返的函数调用 test01(); //有参无返的函数调用 test02(100); //无参有返的函数调用 int num1=test03(); cout << "num1 = " << num1 << endl; //有参有返的函数调用 int num2=test04(10000); cout << "num2 = " << num2 << endl; system("pause"); return 0; }
5、函数声明
#include <iostream> using namespace std; int max(int a, int b); int main() { int a = 10; int b = 20; cout << max(a, b) << endl; system("pause"); return 0; } int max(int a, int b) { return a > b ? a : b; }
6、函数的分文件编写
函数分文件编写一般有4个步骤
1.创建后级名为.h的头文件
2.创建后缀名为.cpp的源文件
3.在头文件中写函数的声明
4.源文件中写函数的定义
swap.h
#include <iostream> using namespace std; void swap(int a, int b);
swap.cpp文章来源:https://www.toymoban.com/news/detail-684336.html
#include "swap.h" void swap(int a, int b) { int temp = a; a = b; b = temp; cout << "a = " << a << endl; cout << "b = " << b << endl; }
main.cpp文章来源地址https://www.toymoban.com/news/detail-684336.html
#include <iostream> using namespace std; #include "swap.h" int main() { int a = 10; int b = 20; swap(a, b); system("pause"); return 0; }
到了这里,关于函数(个人学习笔记黑马学习)的文章就介绍完了。如果您还想了解更多内容,请在右上角搜索TOY模板网以前的文章或继续浏览下面的相关文章,希望大家以后多多支持TOY模板网!