C/C++基础入门系列
写在前面的话
C++学了一段时间了,现在在整理笔记,作为备份和分享,会一点点的连载上来,如果此时的你在看这篇文章,而且想学C/C++,本篇系列文章或许能帮助你打基础,为了方便大家,代码我也直接码在上面了,如果复制粘贴都懒得做的话,过段时间我会把整理好的代码打包传到下载里面。
目录
第一部分 HelloWorld的起点
第二部分 初探数据类型(一)
第三部分 初探数据类型(二)
第四部分 认识运算符(一)
第五部分 认识运算符(二)
第六部分 理清思路,写好逻辑结构(一)
第七部分 理清思路,写好逻辑结构(二)
第八部分 理清思路,写好逻辑结构(三)
第九部分 数据处理神器之数组(一)
第十部分 数据处理神器之数组(二)
第十一部分 写好函数,学会功能复用(一)
第十二部分 写好函数,学会功能复用(二)
第十二部分 写好函数,学会功能复用(二)
6.5 函数常见样式
常见函数样式有四种:
- 无参无返
- 有参无返
- 无参有返
- 有参有返
示例:
#include<iostream>
using namespace std;
// 无参无返
void test01() {
//void a = 10; // 无类型不可以创建变量,因为无法分配内存
cout << "test01" << endl;
//test01(); // 调用函数
}
// 有参无返
void test02(int a) {
cout << "test03\t参数为:" << a << endl;
}
// 无参有返
int test03() {
return 1000;
}
// 有参有返
int test04(int a) {
return a + 1;
}
int main() {
test01();
test02(100);
cout << "test03返回值为:" << test03() << endl;
cout << "test04返回值为:" << test04(100) << endl;;
system("pause");
return 0;
}
6.6 函数的声明
作用: 告诉编译器函数名称及如何调用函数,函数的实际主体可以单独定义。
- 函数的声明可以多次,但是函数的定义只能有一次、
示例:
#include<iostream>
using namespace std;
// 当定义在main后面时,需要声明
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.7 函数的分文件编写
作用: 让代码结构更清晰
函数分文件编写一般有四个步骤
- 创建后缀名为.h的头文件
- 创建后缀名为.cpp的源文件
- 在头文件中写函数的声明
- 在源文件中写函数的定义
示例:
//#swap.h文件
#include<iostream> // swap.cpp中用到该库
using namespace std;
// 函数声明
void swap(int a, int b);
// swap.cpp文件
#include "swap.h" // 双引号表示自定义头文件
void swap(int a, int b) {
int temp = a;
a = b;
b = temp;
cout << "交换后:" << endl;
cout << "a = " << a << endl;
cout << "b = " << b << endl;
}
// 主程序文件
#include<iostream>
using namespace std;
#include"swap.h"
int main() {
int a = 10;
int b = 20;
swap(a, b);
system("pause");
return 0;
}