C++基础语法

Published on with 0 views and 0 comments

一、C++初识

1.1 第一个C++程序

hello world运行代码

#include <iostream>
using namespace std;
int main() {
	cout << "Hello world" << endl;
	system("pause");
	return 0;
}

1.2 注释

  • 单行注释 //描述信息
  • 多行注释 /*描述信息*/
#include <iostream>
using namespace std;
//单行注释
/*
* 多行注释
* 多行注释
* 多行注释
*/
int main() {
	cout << "Hello world" << endl;
	system("pause");
	return 0;
}

1.3 变量

创建语法:变量类型 变量名=变量值;

#include <iostream>
using namespace std;
//单行注释

int main() {
	/*
	*   变量名由数字、字母、下划线组成,以字母或下划线开头
	*	变量类型 变量名   变量值
	*	int        a    =   10;
	*/
	int a = 10;
	cout << a << endl;
	cout << "Hello world" << endl;
	system("pause");
	return 0;
}

1.4 常量

常量在程序运行过程中值不会改变

有两种定义常量的方法

  • #define 定义常量
    • 语法:#define 常量名 常量值
  • const定义常量
    • **语法:**const 常量类型 常量名称 = 常量值;
#include <iostream>
using namespace std;

// define定义常量
#define DAY 7
int main() {
	// DAY = 14; 修改常量会报错
	cout << "一周有" << DAY << "天"<< endl;

	// const定义常量
	const int totalMonth = 12;
	// totalMonth = 24; 修改常量会报错
	cout << "一年有" << totalMonth << "月" << endl;
	system("pause");
	return 0;
}

1.5 关键字

c++中的保留字不能用作常量名、变量名或其他标识符名称

image.png

#include <iostream>
using namespace std;
int main() {
	// 使用关键字int作为变量名报错
	// int int a = 10;
	system("pause");
	return 0;
}

1.6 标识符命名规则

  • 标识符不能是关键字
  • 标识符只能由数字\字母\下划线组成
  • 第一个字母必须是字母或下划线
  • 标识符中字母区分大小写
#include <iostream>
using namespace std;
int main() {
	// 标识符不可以是关键字
	// int int a =  10;

	// 标识符只能由数字\字母\下划线组成
	int abc = 10;
	int _abc = 10;
	int _abc123 = 10;

	// 标识符只能由字母或者下划线开头
	// int 123abc = 123;

	// 标识符区分大小写
	int aaa = 10;
	cout << aaa << endl;
	//cout << AAA << endl;
	system("pause");
	return 0;
}

二、数据类型

数据类型决定了变量存储得大小和布局,该范围内的值都可以存储在内存中

2.1 整型

整型变量表示的是整数类型的数据

image.png

#include <iostream>
using namespace std;

int main() {
	// 短整型
	short num1 = 10;
	// 整形
	int num2 = 10;
	// 长整型
	long num3 = 10;
	// 长长整型
	long long num4 = 10;
	cout << "num1=" << num1 << endl;
	cout << "num2=" << num2 << endl;
	cout << "num3=" << num3 << endl;
	cout << "num4=" << num4 << endl;
	system("pause");
	return 0;
}

2.2 sizeof关键字

**作用:**sizeof可以统计数据类型所占内存大小

**语法:**size(数据类型/变量)

#include <iostream>
using namespace std;
int main() {
	// 整型 short int long long long
	short num1 = 10;
	cout << "short占用的内存空间=" << sizeof(num1) << endl;


	int num2 = 10;
	cout << "int占用的内存空间=" << sizeof(int) << endl;

	long num3 = 10;
	cout << "long占用的内存空间=" << sizeof(long) << endl;

	long long num4 = 10;
	cout << "long long占用的内存空间=" << sizeof(long long) << endl;
	system("pause");
	return 0;
}

2.3 浮点型

浮点型分为单精度float和双精度double

image.png

#include <iostream>
using namespace std;
int main() {
	float f1 = 3.14f;
	cout << "f1=" << f1 << endl;
	cout << "float所占内存=" << sizeof(float) << endl;

	double d1 = 3.14;
	cout << "d1=" << d1 << endl;
	cout << "double所占内存=" << sizeof(double) << endl;

	// 科学计数法
	float f2 = 3e2; //3*10^2=300
	cout << "f2=" << f2 << endl;

	float f3 = 3e-2;//3*0.1^2=0.03
	cout << "f3=" << f3 << endl;

	system("pause");
	return 0;
}

2.4 字符型

字符型用于显示单个字符

  • c++中的字符变量只占用1个字节
  • 字符型变量并不是把字符本身放到内存中存储,而是将对应的ASCII编码放入到存储单元
#include <iostream>
using namespace std;
int main() {
	// 字符型变量创建方式
	char ch = 'a';
	cout << ch << endl;

	// 字符型变量所占内存大小
	cout << "char所占内存大小="<<sizeof(char) << endl;

	// 字符型变量常见错误
	// char ch2 = "a";字符型变量用单引号
	// char ch3 = 'abcd';字符型变量单引号内只能有一个字符

	// 字符型变量对应的ASCII值
	cout << (int)ch << endl;

	system("pause");
	return 0;
}

2.5 转义字符

转义字符用来表示不能显示得ASCII值

image.png

#include <iostream>
using namespace std;
int main() {
	// 换行符
	cout << "hello world\n";
	// 反斜杠
	cout << "\\" << endl;
	//水平制表符 \t输出一个tab位
	cout << "Long\tHello World" << endl;
	system("pause");
	return 0;
}

2.6 字符串

  • 字符数组表示 char 变量名[] = "字符串值";
  • 字符串表示 string 变量名 = "字符串值";
#include <iostream>
#include <string>
using namespace std;

int main() {
	// 字符数组表示
	char str1[] = "hello world";
	cout << str1 << endl;

	//
	string str2 = "hello world";
	cout << str2 << endl;;
	system("pause");
	return 0;
}

2.7 布尔类型

布尔类型用于表示假或真,只有两个值

  • true,本质为非0的值
  • false,本质为0
#include <iostream>
using namespace std;

int main() {
	bool flag = false;
	bool flag1 = true;
	cout << flag << endl;
	cout << flag1 << endl;

	cout << "bool类型所占内存空间="<<sizeof(bool) << endl;
	system("pause");
	return 0;
}

2.8 数据的输入

使用cin输入数据,语法cin >> 接收输入值的变量

#include <iostream>
#include <string>
using namespace std;

int main() {
	int a;
	cout << "请输入整型变量a" << endl;
	cin >> a;
	cout << "整型变量a="<<a << endl;

	double d;
	cout << "请输入浮点型变量d" << endl;
	cin >> d;
	cout << "浮点型变量d=" << d << endl;

	char ch;
	cout << "请输入字符型变量ch" << endl;
	cin >> ch;
	cout << "字符型变量ch=" << ch << endl;


	string str;
	cout << "请输入字符串型变量str" << endl;
	cin >> str;
	cout << "字符串变量str=" << str << endl;


	bool flag;
	cout << "请输入布尔类型变量flag" << endl;
	cin >> flag;
	cout << "布尔类型变量flag=" << flag << endl;

	system("pause");
	return 0;
}

三、运算符

运算符是一种告诉编译器执行特定数学或逻辑操作的符号

运算符类型作用
算术运算符处理四则运算
赋值运算符将表达式的值赋给变量
比较运算符比较表达式,返回一个真或假值
逻辑运算符根据表达式的值返回真或假
位运算符位运算符作用于位,并逐位执行操作

image.png

3.1 算数运算符

算数运算符用于进行四则运算

运算符描述
+把两个操作数相加
-从第一个操作数中减去第二个操作数
*把两个操作数相乘
/分子除以分母
%取模运算符,整除后的余数
++自增运算符,整数值增加 1
--自减运算符,整数值减少 1

3.1.1 加减乘除

#include <iostream>
using namespace std;

int main() {
	int a = 10;
	int b = 3;
	cout << a + b << endl;
	cout << a - b << endl;
	cout << a * b << endl;
	cout << a / b << endl;// 两个整数相除依然是整数
	cout << (float)a / b << endl;// 将被除数转为小数则可以相除
	cout << a / (float)b << endl;// 将除数转为小数则可以相除
	// cout << a / 0 << endl;除数不能为0
	system("pause");
	return 0;
}

3.1.2 取模

#include <iostream>
using namespace std;

int main() {
	// 取模运算就是求余数
	int a = 10;
	int b = 3;
	cout << a % b << endl; 

	int c = 20;
	cout << a % c << endl;

	// cout << a % 0 << endl; 除数不能为0

	/*
	* 取模运算不能出现小数
	* cout << 3 % (float)3 << endl; 
	* cout << (float)3 % 3 << endl; 
	* cout << (float)3 % (float)3 << endl; 
	*/ 
	system("pause");
	return 0;
}

3.1.3 递增递减

变量值自增/减1

  • 前置递增/递减,先增/减后用
  • 后置递增/递减,先用后增/减
#include <iostream>
using namespace std;

int main() {
	// 前置递增
	int a1 = 10;
	++a1;
	cout << "++a1=" << a1 << endl;

	// 后置递增
	int a2 = 10;
	a2++;
	cout << "a2++=" << a2 << endl;

	// 前置和后置的区别,前置先加在用,后置先用在加
	int a3 = 10;
	cout << "++a3=" << ++a3 << endl;//先加再用,输出11
	cout << "a3++=" << a3++ << endl;//先用在加,输出11后加1
	cout << "a3=" << a3 << endl;// 输出12
	system("pause");
	return 0;
}

3.2 赋值运算符

用于将表达式的值赋值给变量

运算符描述实例
=简单的赋值运算符,把右边操作数的值赋给左边操作数C = A + B 将把 A + B 的值赋给 C
+=加且赋值运算符,把右边操作数加上左边操作数的结果赋值给左边操作数C += A 相当于 C = C + A
-=减且赋值运算符,把左边操作数减去右边操作数的结果赋值给左边操作数C -= A 相当于 C = C - A
*=乘且赋值运算符,把右边操作数乘以左边操作数的结果赋值给左边操作数C *= A 相当于 C = C * A
/=除且赋值运算符,把左边操作数除以右边操作数的结果赋值给左边操作数C /= A 相当于 C = C / A
%=求模且赋值运算符,求两个操作数的模赋值给左边操作数C %= A 相当于 C = C %
#include <iostream>
using namespace std;

int main() {
	// 赋值运算符

	// =
	int a1 = 10;
	a1 = 2;
	cout << "a1为10,a1=2结果为" << a1 << endl;


	// +=
	int a2 = 10;
	a2 += 2;// a2=a2+2
	cout << "a2为10,a2+=2结果为" << a2 << endl;

	// -=
	int a3 = 10;
	a3 -= 2;// a3=a3-2
	cout << "a3为10,a3-=2结果为" << a3 << endl;

	// *=
	int a4 = 10;
	a4 *= 2;// a4=a4*2
	cout << "a4为10,a4*=2结果为" << a4 << endl;

	// /=
	int a5 = 10;
	a5 /= 2;// a5=a5/2
	cout << "a5为10,a5/=2结果为" << a5 << endl;

	// %=
	int a6 = 10;
	a6 %= 2; // a6=a6%2
	cout << "a6为10,a6%=2结果为" << a6 << endl;

	return 0;
}

3.3 比较运算符

用于表达式的比较,返回一个真值或假值

运算符描述
==检查两个操作数的值是否相等,如果相等则条件为真。
!=检查两个操作数的值是否相等,如果不相等则条件为真。
>检查左操作数的值是否大于右操作数的值,如果是则条件为真。
<检查左操作数的值是否小于右操作数的值,如果是则条件为真。
>=检查左操作数的值是否大于或等于右操作数的值,如果是则条件为真。
<=检查左操作数的值是否小于或等于右操作数的值,如果是则条件为真。
#include <iostream>
using namespace std;

int main() {
	int a = 10, b = 20;
	cout << "a为10,b为20" << endl;
	cout << "a==b结果为" << (a == b) << endl;
	cout << "a!=b结果为" << (a != b) << endl;
	cout << "a>b结果为" << (a > b) << endl;
	cout << "a>=b结果为" << (a >= b) << endl;
	cout << "a<b结果为" << (a < b) << endl;
	cout << "a<=b结果为" << (a <= b) << endl;
	system("pause");
	return 0;
}

3.4 逻辑运算符

用于表达式的比较,返回一个真值或假值

image.png

#include <iostream>
using namespace std;

int main() {
	int a = 1, b = 0;
	cout << "a&&b=" << (a && b) << endl;
	cout << "a||b=" << (a || b) << endl;
	cout << "!a=" << !a << endl;// 取反
	cout << "!!a=" << !!a << endl;// 两次取反
	system("pause");
	return 0;
}

3.5 位运算符

col1col2
位与(&)对两个数进行位与操作,只有对应的两个位都为1时,结果位才为1
位或(\|)对两个数进行位或操作,只要对应的两个位中有一个为1时,结果位就为1
位异或(^)对两个数进行位异或操作,只有对应的两个位不同,结果位才为1
位非(~)对数的每一位进行取反操作,即将1变为0,将0变为1
左移(<<)将数的所有位向左移动指定的位数,右边空出的位用0填充
右移(>>)将数的所有位向右移动指定的位数,对于无符号数,左边空出的位用0填充;
对于有符号数,空出的位可能用符号位填充,这取决于具体的实现。
#include <iostream>
using namespace std;

int main() {
    unsigned int a = 5; // 二进制表示: 00000101
    unsigned int b = 9; // 二进制表示: 00001001

    // 位与操作
    cout << "a & b = " << (a & b) << endl; // 结果是1 (00000001)

    // 位或操作
    cout << "a | b = " << (a | b) << endl; // 结果是13 (00001101)

    // 位异或操作
    cout << "a ^ b = " << (a ^ b) << endl; // 结果是12 (00001100)

    // 位非操作
    cout << "~a = " << (~a) << endl; // 结果是一个很大的数,因为~操作符取反了a的所有位

    // 左移操作
    cout << "a << 1 = " << (a << 1) << endl; // 结果是10 (00001010), 相当于乘以2

    // 右移操作
    cout << "a >> 1 = " << (a >> 1) << endl; // 结果是2 (00000010), 相当于除以2

    return 0;
}

四、流程控制结构

c++支持三种程序运行结构

  • 顺序结构:按顺序执行,不发生跳转
  • 选择结构:依据条件是否满足,有选择的执行相应功能
  • 循环结构:依据条件是否满足,循环多次执行某代码片段

4.1 选择结构

image.png

语句描述
if 语句一个if 语句 由一个布尔表达式后跟一个或多个语句组成。
if...else 语句一个if 语句 后可跟一个可选的 else 语句 ,else 语句在布尔表达式为假时执行。
嵌套 if 语句您可以在一个if 或 else if 语句内使用另一个 if 或 else if 语句。
switch 语句一个switch 语句允许测试一个变量等于多个值时的情况。
嵌套 switch 语句您可以在一个switch 语句内使用另一个 switch语句。

4.1.1 if语句

4.1.1 单行if语句

if(条件){代码}

#include<iostream>
using namespace std;
int main() {
	float score;
	cout << "请输入一个分数" << endl;
	cin >> score;
	cout << "用户score=" << score << endl;
	if (score > 600) {
		cout << "分数达标" << endl;
	}

	system("pause");
	return 0;
}
4.1.2 多行if语句

if(条件){代码}else{代码}

image.png

#include<iostream>
using namespace std;
int main() {
	float score;
	cout << "请输入一个分数" << endl;
	cin >> score;
	cout << "用户score=" << score << endl;
	if (score > 600) {
		cout << "分数达标" << endl;
	}else {
		cout << "分数不达标" << endl;
	}
	system("pause");
	return 0;
}
4.1.3 多条件if语句

if(条件){代码}else if(条件){代码}.....else{代码}

image.png

#include<iostream>
using namespace std;
int main() {
	float score;
	cout << "请输入一个分数" << endl;
	cin >> score;
	cout << "用户score=" << score << endl;
	if (score >= 600) {
		cout << "S级" << endl;
	}
	else if (score >= 500 && score < 600) {
		cout << "A级" << endl;
	}
	else if (score >= 400 && score < 500) {
		cout << "B级" << endl;
	}
	else {
		cout << "不达标" << endl;
	}
	system("pause");
	return 0;
}
4.1.4 嵌套if语句
#include<iostream>
using namespace std;
int main() {
	float score;
	cout << "请输入一个分数" << endl;
	cin >> score;
	cout << "用户score=" << score << endl;
	if (score >= 600) {
		if (score >= 700) {
			cout << "SSS级" << endl;
		}
		else if (score >= 650 && score < 700) {
			cout << "SS级" << endl;
		}
		else {
			cout << "S级" << endl;
		}

	}
	else if (score >= 500 && score < 600) {
		cout << "A级" << endl;
	}
	else if (score >= 400 && score < 500) {
		cout << "B级" << endl;
	}
	else {
		cout << "不达标" << endl;
	}
	system("pause");
	return 0;
}

4.1.2 三目运算符

Exp1 ? Exp2 : Exp3;

若Exp1的值为真,则执行Exp2,并返回Exp2的结果;

若Exp1的值为假,则执行Exp3,并返回Exp3的结果;

#include<iostream>
using namespace std;
int main() {
	float score;
	cout << "请输入一个分数" << endl;
	cin >> score;
	cout << "本次四级考试结果=" << (score >= 425 ? "及格" : "不及格") << endl;
	system("pause");
	return 0;
}

4.1.3 switch语句

一个 switch 语句允许测试一个变量等于多个值时的情况。每个值称为一个 case,且被测试的变量会对每个 switch case 进行检查。

  • switch 语句中的 expression 必须是一个整型或枚举类型,或者是一个 class 类型,其中 class 有一个单一的转换函数将其转换为整型或枚举类型
  • case 的 constant-expression 必须与 switch 中的变量具有相同的数据类型,且必须是一个常量或字面量
  • 当被测试的变量等于 case 中的常量时,case 后跟的语句将被执行,直到遇到 break 语句为止
  • 当遇到 break 语句时,switch 终止,控制流将跳转到 switch 语句后的下一行
  • 一个 switch 语句可以有一个可选的 default case,出现在 switch 的结尾。default case 可用于在上面所有 case 都不为真时执行一个任务。default case 中的 break 语句不是必需的

语法如下:

switch(expression){
    case constant-expression  :
       statement(s);
       break; // 可选的
    case constant-expression  :
       statement(s);
       break; // 可选的
  
    // 您可以有任意数量的 case 语句
    default : // 可选的
       statement(s);
}
#include<iostream>
using namespace std;
int main() {
	int score;
	cout << "请输入一个评分(0-10)" << endl;
	cin >> score;
	switch (score) {
		case 10: 
			cout << "经典"<< endl;
			break;
		case 9:
			cout << "经典" << endl;
			break;
		case 8:
			cout << "非常好" << endl;
			break;
		case 7:
			cout << "非常好" << endl;
			break;
		case 6:
			cout << "一般" << endl;
			break;
		case 5:
			cout << "一般" << endl;
			break;
		case 4:
			cout << "烂片" << endl;
			break;
		case 3:
			cout << "烂片" << endl;
			break;
		case 2:
			cout << "烂片" << endl;
			break;
		case 1:
			cout << "烂片" << endl;
			break;
		case 0:
			cout << "烂片" << endl;
			break;
		default:
			cout << "请输入正确的评分" << endl;
	}
	system("pause");
	return 0;
}

4.2 循环结构

4.2.1 while循环

语法while(条件){代码}

image.png

#include<iostream>
using namespace std;
int main() {
	int a = 0;
	while (a < 10) {
		cout << a << endl;
		a++;
	}
	system("pause");
	return 0;
}

4.2.2 do...while循环

语法do{循环语句}while(循环条件)

条件表达式出现在循环的尾部,所以循环中的 statement(s) 会在条件被测试之前至少执行一次

image.png

#include<iostream>
using namespace std;
int main() {
	int a = 0;
	do {
		cout << a << endl;
		a++;
	} while (a < 10);
	system("pause");
	return 0;
}

4.2.3 for循环

for ( init; condition; increment )
{
   statement(s);
}

#include<iostream>
using namespace std;
int main() {
	for (int a = 0; a < 10; a++) {
		cout << a << endl;
	}
	system("pause");
	return 0;
}

4.2.4 嵌套循环

在循环体中嵌套循环

#include<iostream>
using namespace std;
int main() {
	for (int a = 0; a < 10;a++ ) {
		for (int b = 0; b < 10; b++) {
			cout << "* ";
		}
		cout << endl;
	}
	system("pause");
	return 0;
}

4.3 跳转语句

用于跳出选择结构或者循环结构

控制语句描述
break 语句终止循环 或 switch 语句,程序流将继续执行紧接着 循环 或 switch 的下一条语句。
continue 语句引起循环跳过主体的剩余部分,立即重新开始测试条件。
goto 语句将控制转移到被标记的语句。但是不建议在程序中使用 goto 语句。

4.3.1 break语句

  • 出现在switch中,终止case并跳出switch
  • 出现在循环语句中,种植当前循环语句
  • 出现在嵌套循环的内循环中,终止内循环,外循环继续
#include<iostream>
using namespace std;
int main() {
	// break用于switch
	int hardModal;
	cout << "请选择模式" << endl;
	cout << "1、困难" << endl;
	cout << "2、普通" << endl;
	cout << "3、休闲" << endl;
	cin >> hardModal;
	switch (hardModal) {
		case 1:
			cout << "选择困难模式" << endl;
			break;
		case 2:
			cout << "选择普通模式" << endl;
			break;
		case 3:
			cout << "选择休闲模式" << endl;
			break;
		default:
			cout << "请输入正确的模式" << endl;
	}
	// break用于循环
	for (int a = 0; a < 10; a++) {
		cout << a << " ";
		if (a == 3) {
			cout << "a==3,不在执行后续操作" << endl;
			break;
		}
	}

	// break用于循环嵌套
	for (int a = 0; a < 10; a++) {
		for (int b = 0; b <= a+1; b++) {
			cout << "*";
			if (b == a) {
				break;
			}
		}
		cout << endl;
	}
	system("pause");
	return 0;
}

4.3.2 continue语句

continue 会跳过当前循环中的代码,强迫开始下一次循环

image.png

#include<iostream>
using namespace std;
int main() {
	// 在for循环中使用continue
	for (int i = 0; i < 10; i++) {
		if (i % 2 == 0) {
			continue;
		}
		cout << i;
	}
	cout << endl;
	// 在while循环中使用continue
	int max = 0;
	while (max < 10) {
		if (max % 3 == 0) {
			max++;
			continue;
		}
		cout << max;
		max++;
	}
	cout << endl;
	// 在do...while循环中使用continue
	int max1 = 0;
	do {
		if (max1 % 4 == 0) {
			max1++;
			continue;
		}
		cout << max1;
		max1++;
	} while (max1 < 10);

	system("pause");
	return 0;
}

4.3.3 goto语句

将控制转移到被标记的语句。但是不建议在程序中使用 goto 语句,语法如下

goto label;
..
.
label: statement;

image.png

#include<iostream>
using namespace std;
int main() {
	cout << "1.***" << endl;
	goto LOOP;
	cout << "2.***" << endl;
	cout << "3.***" << endl;
	cout << "4.***" << endl;
    LOOP:
	cout << "5.***" << endl;
	system("pause");
	return 0;
}

五、数组

5.1 概述

数组用于存储一个固定大小的相同类型元素的顺序集合

特点:

  • 数组中每个元素是相同的数据类型
  • 数组在内存中是连续存储的
  • 数组访问下标都是从0开始

5.1 一维数组

5.1.1 定义

三种定义方式

  • 数组类型 数组名[数组长度];
  • 数据类型 数组名[数组长度]={元素1,元素2,元素3...};
  • 数据类型 数组名[]={元素1,元素2,元素3...};
#include <iostream>
using namespace std;
int main() {
	//数组类型 数组名[数组长度];
	int arr1[5];
	arr1[0] = 0;
	arr1[1] = 1;
	arr1[2] = 2;
	arr1[3] = 3;
	arr1[4] = 4;

	cout << "arr1[0]=" << arr1[0] << endl;
	cout << "arr1[1]=" << arr1[1] << endl;
	cout << "arr1[2]=" << arr1[2] << endl;
	cout << "arr1[3]=" << arr1[3] << endl;
	cout << "arr1[4]=" << arr1[4] << endl;
	cout << endl;


	//数据类型 数组名[数组长度]={元素1,元素2,元素3...};
	int arr2[5] = {1,2,3,4,5};
	//若初始化数字与数组长度不符合,则空的数组元素值会赋数组类型的默认值
	//int arr2[5] = { 1,2,3 };
	cout << "arr2[0]=" << arr2[0] << endl;
	cout << "arr2[1]=" << arr2[1] << endl;
	cout << "arr2[2]=" << arr2[2] << endl;
	cout << "arr2[3]=" << arr2[3] << endl;
	cout << "arr2[4]=" << arr2[4] << endl;
	cout << endl;

	//数据类型 数组名[]={元素1,元素2,元素3...};
	int arr3[] = { 2,3,4,5,6 };
	cout << "arr3[0]=" << arr3[0] << endl;
	cout << "arr3[1]=" << arr3[1] << endl;
	cout << "arr3[2]=" << arr3[2] << endl;
	cout << "arr3[3]=" << arr3[3] << endl;
	cout << "arr3[4]=" << arr3[4] << endl;
	system("pause");
	return 0;
}

5.1.2 数组名

  • 通过数组名可以获取数组所占内存
  • 通过数组名可以获取数组首地址
#include <iostream>
using namespace std;
int main() {
	int arr1[5] = { 1,2,3,4,5 };

	// 通过数组名获取数组所占内存
	cout << "数组占用内存=" << sizeof(arr1) << endl;
	// 通过数组名获取数组首地址
	cout << "数组首地址=" << arr1 << endl;
	system("pause");
	return 0;
}

5.2 二维数组

5.2.1 定义

  • 数据类型 数组名[行数][列数]
  • 数据类型 数组名[行数][列数]={{数据1,数据2},{数据3,数据4}.....}
  • 数据类型 数组名[行数][列数]={数据1,数据2,数据3,数据4.....}
  • 数据类型 数组名[][列数]={数据1,数据2,数据3,数据4.....}
#include <iostream>
using namespace std;
int main() {
	//数据类型 数组名[行数][列数]
	int arr1[3][3];
	cout << "给arr1赋值并输出" << endl;
	for (int h = 0; h < 3; h++) {
		for (int l = 0; l < 3; l++) {
			arr1[h][l] = h + l;
			cout << arr1[h][l] << " ";
		}
		cout << endl;
	}

	//数据类型 数组名[行数][列数] = { {数据1,数据2},{数据3,数据4}..... }
	int arr2[3][3] = {
		{1,2,3},
		{4,5,6},
		{7,8,9}
	};
	cout << "输出arr2" << endl;
	for (int h = 0; h < 3; h++) {
		for (int l = 0; l < 3; l++) {
			cout << arr2[h][l] << " ";
		}
		cout << endl;
	}
	//数据类型 数组名[行数][列数]={数据1,数据2,数据3,数据4.....}
	int arr3[3][3] = { 1,2,3,4,5,6,7,8,9 };
	cout << "输出arr3" << endl;
	for (int h = 0; h < 3; h++) {
		for (int l = 0; l < 3; l++) {
			cout << arr3[h][l] << " ";
		}
		cout << endl;
	}
	//数据类型 数组名[][列数]={数据1,数据2,数据3,数据4.....}
	//根据元素个数和行/列数,可以计算出正确的行/列数
	int arr4[][3] = { 1,2,3,4,5,6,7,8,9 };
	cout << "输出arr4" << endl;
	for (int h = 0; h < 3; h++) {
		for (int l = 0; l < 3; l++) {
			cout << arr4[h][l] << " ";
		}
		cout << endl;
	}
	system("pause");
	return 0;
}

5.2.2 数组名

  • 通过数组名可以获取数组所占内存
  • 通过数组名可以获取数组首地址
#include <iostream>
using namespace std;
int main() {
	int arr1[3][3] = {
		{1,2,3},
		{4,5,6},
		{7,8,9}
	};

	// 通过数组名获取数组所占内存
	cout << "数组占用内存=" << sizeof(arr1) << endl;
	cout << "数组第一行占用内存=" << sizeof(arr1[0]) << endl;
	cout << "数组第一个元素占用的内存" << sizeof(arr1[0][0]) << endl;
	cout << "数组行数=" << sizeof(arr1)/sizeof(arr1[0]) << endl;
	cout << "数组列数=" << sizeof(arr1[0])/sizeof(arr1[0][0]) << endl;

	// 通过数组名获取数组首地址
	cout << "数组首地址=" << arr1 << endl;
	system("pause");
	return 0;
}

六、函数

6.1 概述

函数是一组一起执行一个任务的语句

6.2 函数的定义

定义语法如下

return_type function_name( parameter list )
{
   body of the function
   return 表达式
}
  • 返回类型: 一个函数可以返回一个值。return_type 是函数返回的值的数据类型。有些函数执行所需的操作而不返回值,在这种情况下,return_type 是关键字 void 。
  • 函数名称: 这是函数的实际名称。函数名和参数列表一起构成了函数签名。
  • 参数: 参数就像是占位符。当函数被调用时,您向参数传递一个值,这个值被称为实际参数。参数列表包括函数参数的类型、顺序、数量。参数是可选的,也就是说,函数可能不包含参数。
  • 函数主体: 函数主体包含一组定义函数执行任务的语句
  • **return表达式:**函数体内使用return返回函数值
#include <iostream>
using namespace std;

/*
* 返回值类型 int
* 函数名 sumFunc
* 函数参数列表 int num1, int num2
* 函数体 int sum = num1 + num2;
* return表达式 return sum;
*/
int sumFunc(int num1, int num2) {
	int sum = num1 + num2;
	return sum;
}

int main() {
	system("pause");
	return 0;
}

6.3 函数的调用

调用函数时,传递所需参数,如果函数返回一个值,则可以存储返回值

#include <iostream>
using namespace std;

// num1 num2为形参
int addFunc(int num1, int num2) {
	int sum = num1 + num2;
	return sum;
}

int main() {
	int a = 10, b = 10;
	// a b为实参
	int sum = addFunc(a, b);
	cout << "a+b=" << sum << endl;
	system("pause");
	return 0;
}

6.4 参数传递

  • 将实际值传递给函数的形参
  • 形参改变不会改变实参的值
#include <iostream>
using namespace std;

void swapNum(int num1, int num2) {
	cout << "交换前num1=" << num1 << endl;
	cout << "交换前num2=" << num2 << endl;
	int swapNum = num1;
	num1 = num2;
	num2 = swapNum;
	cout << "交换后num1=" << num1 << endl;
	cout << "交换后num2=" << num2 << endl;

}

int main() {
	int a = 10, b = 20;
	cout << "执行交换前a=" << a << endl;
	cout << "执行交换前b=" << b << endl;
	swapNum(a, b);
	cout << "执行交换后a=" << a << endl;
	cout << "执行交换后b=" << b << endl;
	system("pause");
	return 0;
}

6.5 函数声明

函数声明会告诉编译器函数名称及如何调用函数

函数声明语法:返回值类型 函数名(参数列表);

#include <iostream>
using namespace std;

// 函数声明
int max(int a, int b);

int main() {
	int a = 10, b = 20;
	cout << max(a, b) << endl;
	system("pause");
	return 0;
}

int max(int a, int b) {
	return a > b ? a : b;
}

6.6 函数跨文件编写

为了使代码结构清晰,需要将将函数放在不同的文件中,需要谁用的时候在调用,通过一下步骤实现

  • 创建.h头文件
  • 创建.cpp源文件
  • 在头文件声明函数
  • 在源文件中实现函数

swap.h头文件

#include <iostream>
using namespace std;
void swap(int num1, int num2);

swap.cpp源文件

#include "swap.h"
void swap(int num1, int num2) {
	cout << "交换前num1=" << num1 << endl;
	cout << "交换前num2=" << num2 << endl;
	int swapNum = num1;
	num1 = num2;
	num2 = swapNum;
	cout << "交换后num1=" << num1 << endl;
	cout << "交换后num2=" << num2 << endl;
}

main函数

#include <iostream>
using namespace std;
#include "swap.h"


int main() {
	int a = 10, b = 20;
	cout << "执行交换前a=" << a << endl;
	cout << "执行交换前b=" << b << endl;
	swap(a, b);
	cout << "执行交换后a=" << a << endl;
	cout << "执行交换后b=" << b << endl;
	system("pause");
	return 0;
}

七、指针

7.1 概述

通过指针可以访问内存

7.2 指针的定义和使用

定义指针语法:指针基类型 *变量名;

#include <iostream>
using namespace std;
int main() {
	// 1、定义一个指针
	int a = 10;
	int *p;// 创建指针
	p = &a;// p只想变量a的内存地址
	cout << "a的地址=" << &a << endl;
	cout << "指针p=" << p << endl;// 指针指向的内存地址
	// 2、指针的使用
	cout << "指针*p=" << *p << endl;// 指针指向的内存地址中存储的值
	cout << "指针&p=" << &p << endl;// 这是指针P自己的存储地址
	system("pause");
	return 0;
}

7.3 指针所占的内存空间

  • 在32位操作系统下,指针占4字节
  • 在64位操作系统下,指针占8字节
#include <iostream>
using namespace std;
int main() {
	int a = 10;
	int* p = &a;
	cout << "int*所占的内存大小" << sizeof(p) << endl;
	cout << "int*所占的内存大小" << sizeof(int *) << endl;
	cout << "double*所占的内存大小" << sizeof(double*) << endl;
	system("pause");
	return 0;
}

7.4 空指针和野指针

7.4.1 空指针

**NULL是一个值为0的宏常量:#define NULL ((void )0)*,用于初始化指针,空指针指向的内存空间是不可访问的

#include <iostream>
using namespace std;
int main() {
	int* p = NULL;
	cout << p << endl;// 指针指向的内存地址
	cout << &p << endl;// 指针自己所在的内存地址
	cout << *p << endl;// 指针指向的内存地中存储的值
	system("pause");
	return 0;
}

7.4.2 野指针

指针指向非法的内存空间

注:野指针不会直接引发错误,操作野指针指向的内存区域才会出问题。

#include <iostream>
using namespace std;
int main() {
	int* p = (int *)0x1100;
	*p = 100;// 指针指向的内存地中存储的值,调试执行报错
	system("pause");
	return 0;
}

7.5 const修饰指针

  • const修饰指针--常量指针,指针指向可以改,指针指向的常量不能修改
  • const修饰常量--指针常量,指针指向不可以修改,指针指向的值可以修改
  • const既修饰指针也修饰常量,指针指向不可以修改,指针指向的值不可以修改
#include <iostream>
using namespace std;
int main() {
	int a = 10, b = 10;

	// const修饰指针,常量指针
	const int* p1 = &a;
	// 指针指向可以改,指针指向的值不可以改
	//*p1 = 20;
	p1 = &b;


	// const修饰常量,指针常量
	int* const p2 = &a;
	// 指针指向不可以改,指针指向的值可以改
	*p2 = 20;
	//p2 = &b;


	// const修饰常量和指针
	const int* const p3 = &a;
	//*p3 = 20;
	//p3 = &b;
	system("pause");
	return 0;
}

7.6 指针和数组

指针的算数运算详见7.8

#include <iostream>
using namespace std;
int main() {

	int arr[] = { 1,2,3,4 };
	int* p = arr;// arr就是数组的首地址

	/*
	* 数组内存空间连续,int占用四个字节,p是指针指向的内存地址,
	* ++让他指向下一个内存空间,跨越的内存空间耶斯四个字节
	*/
	for (int i = 0; i < 4; i++) {
		cout << *p;
		p++; ////地址偏移+1,等价偏移到下一个元素地址
	}
	system("pause");
	return 0;
}
#include <iostream>
using namespace std;

int main() {
	int arr[3] = { 1,2,3 };
	// 定义一个数组,里面存储指针
	int* ptrArr[3];
	for (int i = 0; i < 3; i++) {
		// 指针数组第i个元素存储素组第i个元素的地址
		ptrArr[i] = &arr[i];
	}
	// 遍历指针数组指向的值
	for (int i = 0; i < 3; i++) {
		cout << *ptrArr[i] << endl;
	}
	system("pause");
	return 0;
}

7.7 指针和函数

指针作为函数形参的参数可以修改实参的值

#include <iostream>
using namespace std;

void swap(int* a, int* b) {
	int temp = *a;
	*a = *b;
	*b = temp;
}
int main() {
	int a = 1, b = 2;
	cout << "交换前" << endl;
	cout << "a=" << a << endl;
	cout << "b=" << b << endl;
	swap(&a, &b);
	cout << "交换后" << endl;
	cout << "a=" << a << endl;
	cout << "b=" << b << endl;
	system("pause");
	return 0;
}
#include <iostream>
using namespace std;

// 函数返回指针
int* sumFunc(int a, int b) {
	int* sum = new int(a+b);
	return sum;
}

int main() {
	int *num = sumFunc(1, 2);
	cout << *num;
	system("pause");
	return 0;
}

7.8 指针的算数运算

可以对指针进行四种算数运算:++、--、+、-

  • 加法运算:当一个指针p加上一个整数n,结果是指针p向前移动n个元素大小
  • 加法运算:当一个指针p减去一个整数n,结果是指针p向后移动n个元素大小
  • 指针与指针之间的减法运算:计算两个指针的距离,结果是两个指针之间的元素个数
  • 指针与整数的比较:使用关键字(>、<、<=、>=)比较指针和整数,常用于判断指针是否指向某个有效的内存位置
#include <iostream>
using namespace std;

int main() {
	int arr[3] = { 1,2,3 };
	int* ptr;
	// 指针中第一个元素的位置
	ptr = arr;
	int index = 0;
	/*
	* ptr是第一个元素的地址,由于数组内存空间连续,
	* 在循环中只要ptr指向的地址小于等于数组最后一个元素的地址即可
	* 循环体中ptr++,会使指针指向整型数组中下一个元素的地址
	*/
	while (ptr <= &arr[2]) {
		cout << "数组第" << index + 1 << "个元素地址" << ptr << endl;
		cout << "数组第" << index + 1 << "个元素值" << *ptr << endl;
		index++;
		ptr++;
	}
	/*
	* p1指向数组第一个元素地址
	* p2指向数组最后一个元素
	* p2-p1得到数组两个元素之间的元素个数
	* 
	*/
	int* p1 = arr;
	int* p2 = &arr[2];
	cout << p2 - p1 << endl;
	system("pause");
	return 0;
}

八、结构体

8.1 概述

结构体属于用户自定义的数据类型

8.2 结构体的定义和使用

创建结构体时struct关键字可以省略

语法 struct 结构体名{结构体成员};

#include <iostream>
using namespace std;
#include <string>
struct Student {
	string name;
	int age;
	float score;
} s3;

int main(){
	// 创建后赋值
	struct Student s1;
	s1.name = "IKun";
	s1.age = 18;
	s1.score = 555.5f;
	cout << "姓名="<< s1.name << "年龄=" << s1.age << "分数=" << s1.score <<endl;

	// 创建时赋值
	struct Student s2 = {"long",19,666.6f};
	cout << "姓名=" << s2.name << "年龄=" << s2.age << "分数=" << s2.score << endl;

	// 定义结构体时创建结构体变量
	s3.name = "Wen";
	s3.age = 17;
	s3.score = 700.5f;
	cout << "姓名=" << s3.name << "年龄=" << s3.age << "分数=" << s3.score << endl;

	system("pause");
	return 0;
}

8.3 结构体数组

将结构体放入数组中存储

#include <iostream>
using namespace std;
#include <string>
struct Student {
	string name;
	int age;
	float score;
};

// 创建结构体时struct关键字可以省略
int main() {

	Student stuArr[3] = {
		{"long",19,666.6f},
		{"wen",20,667.6f},
		{"you",21,668.6f},
	};

	for (int i = 0; i < 3; i++) {
		cout << "姓名=" << stuArr[i].name << "年龄=" << stuArr[i].age << "分数=" << stuArr[i].score << endl;
	}


	system("pause");
	return 0;
}

8.4 结构体指针

利用->操作符可以访问结构体指针访问元素的属性

#include <iostream>
using namespace std;
#include <string>
struct Student {
	string name;
	int age;
	float score;
};

int main03() {
	Student s1 = { "long",19,666.6f };
	cout << "姓名=" << s1.name << "年龄=" << s1.age << "分数=" << s1.score << endl;
	Student* ptr = &s1;
	ptr->name = "wen";
	cout << "姓名=" << ptr->name << "年龄=" << ptr->age << "分数=" << ptr->score << endl;


	system("pause");
	return 0;
}

8.5 结构体嵌套

#include <iostream>
using namespace std;
#include <string>
struct Student {
	string name;
	int age;
	float score;
};
struct Teacher {
	string name;
	int age;
	Student stu;
};

int main() {
	Student s1 = { "long",19,666.6f };
	Teacher t1 = { "wen",99,s1 };
	cout << "教师姓名=" << t1.name << "教师年龄=" << s1.age<< endl;
	cout << "学生姓名=" << t1.stu.name << "年龄=" << t1.stu.age << "分数=" << t1.stu.score << endl;

	system("pause");
	return 0;
}

8.6 结构体作为函数参数

这里要注意传值和传址的区别

#include <iostream>
using namespace std;
#include <string>
struct Student {
	string name;
	int age;
	float score;
};

void printStu(Student stu) {
	cout << "学生姓名=" << stu.name << "年龄=" << stu.age << "分数=" << stu.score << endl;
}

int main() {
	Student s1 = { "long",19,666.6f };
	printStu(s1);


	system("pause");
	return 0;
}

8.7 结构体中const使用场景

这里其实是常量指针的一种应用,可以修改指针指向的位置,但是不能修改数据,这样即避免了形参接收实参时多余的内存开销,也规避了指针数据误操作的风险

#include <iostream>
using namespace std;
#include <string>
struct Student {
	string name;
	int age;
	float score;
};

/*
* 函数参数会赋值传递的stu信息,会在内存中单独开辟一块内存空间存储这部分数据
* 参数是一个数组列表且长度较大会增加程序的内存开销
* 可以使用指针作为参数传址来解决这个问题,但是有误操作的风险,因此加一个const防止误操作
*/ 

void printStu1(const Student* stu) {
	cout << "学生姓名=" << stu->name << "年龄=" << stu->age << "分数=" << stu->score << endl;
}

int main() {
	Student s1 = { "long",19,666.6f };
	printStu1(&s1);


	system("pause");
	return 0;
}

标题:C++基础语法
作者:wenyl
地址:http://www.wenyoulong.com/articles/2024/04/08/1712566794240.html

↑ ↓