C++ 教程 - 01 基础篇

C++介绍

  • 基于C语言,继承了C的所有语法;

  • 静态类型语言,需要先编译,再执行;

  • 贴近底层硬件,运行速度快;
     

  • 支持面向对象、面向泛型,增强版的C;

  • 应用领域
    在这里插入图片描述

  • 编译(Compile),编译器 将整个源代码翻译成机器码(二进制文件),一次性交给计算机执行,如C/C++;

  • 解释(Interpret),由解释器将代码逐行解释为机器码,交给计算机执行,如 python/js ;

  • c++的运行
    在这里插入图片描述

  • 版本C++ 98、C++ 11、 C++ 14、 C++ 17、C++ 20

环境配置

集成开发环境Visual Studio ,编辑、编译;
下载地址
工具 -> 选项 可调整字体等
项目上右键 -> 设为启动项目,做项目切换;
Ctrl + k, c 注释;
Ctrl + k, u 取消注释;

 

第一个cpp程序

#include <iostream>    // 包含头文件
using namespace std;  // 使用std 命名空间


/*多行注释
int, 返回值类型
main,主函数
arr, 形式参数
{}, 函数体
*/
int main(char* arr[]) { //一个项目中仅仅一个main函数
	// cout 输出  cin >> 变量 输入
	// << 流输出运算符
	// endl  结束一行
	cout << "Hello jack" << endl; // 必须分号结束
	
	// 系统调用
	system("pause"); // 暂停
	return 0;
}

在这里插入图片描述
选中源码-右键-编译,可以生成.obj目标文件;
选中项目-右键-生成(build),可以生成exe文件;
查看路径如下:
在这里插入图片描述

 

案例练习

  • 基于函数封装实现功能;
  • 输入用户名,输出欢迎信息;
#include <iostream>    // 包含头文件
using namespace std;  // 使用std 命名空间



// 函数封装 void 表示 函数没有返回值
void welcomeUser() {
	cout << "请输入用户名:" << endl;

	// C++ 支持字符串类型  而C不支持
	string name;

	// 输入
	cin >> name;

	// 输出欢迎信息
	cout << "Welcome " << name << endl;
}


int main(char* arr[]) {
	
	// 调用函数
	welcomeUser();

	// 系统调用
	system("pause"); // 暂停
	return 0;
}

也可以将该函数定义在另一个源文件中,本源文件内仅仅声明即可使用。声明如void welcomeUser(); 是没有函数体的;编译器会自动查找。

 

变量

  • 声明变量,即分配内存;
  • 命名以字母、数字、下划线,不以数字开头;
  • 在代码块{ }内部的变量为局部变量;在所有{}外的变量为全局变量
  • 局部变量必须先初始化赋值,才可以使用;而全局变量默认初始化;
  • 代码块内部,优先查找(作用域最小的)局部变量,使用 :: + 变量 访问全局变量;
#include <iostream>    // 包含头文件
using namespace std;  // 使用std 命名空间


// 定义枚举类型
enum Sex
{
	MALE,  // 默认从0开始
	FEMALE
};


int main(char* arr[]) {
	// 整型定义
	int age; // 变量的声明
	age = 23; // 初始化赋值

	// double  
	double score = 79.534;  // 声明并赋值  为变量定义
	float scoreF = 60.8f;

	// 字符串定义
	string name = "jack";
	string fullName = name + "li";  // 字符串的拼接

	// 布尔
	bool isGood = false;

	// 枚举
	enum Sex sex = MALE; // 定义 并赋值

	// 输出
	cout << "姓名:" << name << endl;
	cout << "全名:" << fullName << endl;
	cout << "性别:" << sex << endl;
	cout << "年龄:" << age << endl;
	cout << "分数:" << score << endl;
	cout << "是否好学生:" << isGood << endl;

	// 系统调用
	system("pause"); // 暂停
	return 0;
}
  • 变量基本类型(本质占用多少内存空间)
    • char, 字符类型 单引号+单字符;1byte;对应ASCII码整数值;
    • short,短整型 2bytes
    • int ,整型 2-4bytes,注意数据溢出,超出范围循环到另一端;一般使用int;
    • long,4bytes
    • long long 8bytes
    • unsigned short/int/long/long long 无符号(非负);
    • unsigned char 无符号的字符
    • float,单精度浮点型 4bytes
    • double 双精度,8bytes
    • string,字符串
    • bool,true/false,本质为整型
    • void 空类型;
    • 整数字面量默认为int; 可以后缀指定 LL 长整型/ ULL无符号长整型
    • 小数字面量默认为double; 指定后缀 f -> float,L -> long double;
    • 字符串的字面量是字符的数组;
       
  • 自定义类型
    • enum,枚举
    • struct,结构体
    • union,共用体
  • sizeof 查看占用内存大小
    • sizeof age
       

常量

  • const 类型 常量名=赋值;值不可更改;
  • #define ABC 5 宏定义常量;
  • 常量值不可更改
     

关系运算符

  • <、<=、 >、>= 优先;
  • ==、!= 次之
  • 表达式返回bool类型

逻辑运算符

&& 同true 则为true ,第一个为false,则不再计算第二个条件;
|| 有一个true 则返回true ,第一个为true,则不再计算第二个条件;
!取反
优先级
在这里插入图片描述

条件运算符

  • 表达式 ?值1 :值2
  • 表达式为true,则取值1;否则取值2
  • 优先级较低,一般使用()包裹;

位运算符

  • ~ 按位取反;
  • << 按位左移、>> 按位右移; 如 int a = 5; a << 2; 一般无符号的数左移、右移;
  • & 按位与,同1则为1;
  • | 按位或,有1则为1;
  • ^ 按位异或,相同则为0,不同则为1;
  • 优先级从上到下依次降低;

类型转换

  • 隐式转换,
    • 短的数据类型向长的数据类型转换;如int -> long long; 4 + 5.5 这里4转为double
    • short/char/bool 一般会转为int;
    • 判断时,0转为false,非0转为true;
    • 赋值时,右侧值类型转为左侧变量的类型;
  • 强制转换,长的类型向短的类型中转换;
    • int age = 5;
    • double aa =(double)age; // C风格
    • double bb = double(age); // C++风格
    • static_cast<double>(age)

分支

  • if …else
if (表达式) {}

if (表达式) {}
else if (表达式) {}
else {}
  • switch
int age = 5;
switch(age){ // 必须传入数值
	case 1: 语句;break;
	case 2: 语句;brea;
	default: 语句;
}

案例1:输入一个人的姓名,分数,输出他的平分等级;
>=90 优秀;
>=80 良好;
>=70中等;
>=60及格;
否则,不及格

#include <iostream>

using namespace std;



int main() {
	// declare
	string name;
	double score;

	cout << "输入姓名:" << endl; // endl换行
	//获取输入
	cin >> name;
	cout << "输入分数:" << endl;
	cin >> score;


	// 判断
	if (score >= 90) {
		cout << name << ":优秀" << endl;
	}
	else if (score >= 80) {
		cout << name << ":良好" << endl;
	}
	else if (score >= 70) {
		cout << name << ":中等" << endl;
	}
	else if (score >= 60) {
		cout << name << ":及格" << endl;
	}
	else {
		cout << name << ":不及格" << endl;
	}

	// system("dir");
	system("pause");
	return 0;
}

 
案例2: 输入绩效等级,输出奖金数额;
使用switch

#include <iostream>

using namespace std;


int main() {
	// declare
	char level;

	cout << "输入等级:" << endl;
	cin >> level;
	
	switch (level) { // 传入数值
	case 'A': cout << 1000 << endl; break;
	case 'B': cout << 500 << endl; break;

	case 'C': cout << 300 << endl; break;
	default: cout << "没有奖励" << endl;
	}

	// system("dir");
	system("pause");
	return 0;
}

 

循环

  • while
  • do…while
  • for
    C是面向过程,为扩展C的功能,开发出了C++,扩展了面向对象、基于泛型的操作;
    C的所有语法在C++中基本都可以使用;
    由于C++的复杂性,基于C++ 实现了java语言,在保留好用的语法的同时,进行了不好的语法的修改;
     
    while循环:
#include <iostream>

using namespace std;


int main() {
	// declare
	char level;

	int i = 3;
	// 用户循环输入
	while (1) {
		
		// 异常捕获
		try
		{
			cout << "输入等级:" << endl;
			cin >> level;

			switch (level) {
			case 'A': cout << 1000 << endl; break;
			case 'B': cout << 500 << endl; break;

			case 'C': cout << 300 << endl; break;
			default: cout << "没有奖励" << endl;
			}
			--i;
			cout << "i:" << 5 / i << endl; //  除0会退出进程
			continue;  // 继续下次循环
		}
		catch (const std::exception&)  // 异常捕获 与java js类似
		{
			cout << "捕获异常" << endl;
			break; // 结束循环
		}
	
	}
	

	// system("dir");
	system("pause");
	return 0;
}

 
do…while:

int i = 10;
do {
	cout << "current i:" << i << endl;
	--i;
}while(i > 0);

 
for循环:

// C 的用法
int i;   
for(i=0; i < 10; i++){ // 满足i<10,则执行代码块,最后执行i++,再判断是否满足条件
	cout << "current i:" << i << endl;
}

// 遍历数组元素  同java
int arr[] = {1, 2, 5, 9};
for (int e : arr) {
	if (e % 5 == 0) {
		continue; // 继续下次循环,后面的代码不再执行
	}
	else if(e / 3 == 3){
		break; // 结束循环

	}else
	cout << e << endl;
}
// 最终输出 1 2 

&nbsp;
goto 标签: 跳转到语句块,不推荐使用

#include <iostream>
using namespace std;


int main() {
	goto laufing; // 语句块 跳转 windows批处理支持goto
	// 声明语句块
laufing: 
	cout << "input your name:" << endl;
	string name;
	cin >> name; // 直接输入空格,不会停止扫描,输入字符串后遇到空格则停止
	// name.empty()  是否为空
	// name.length() 长度
	// name.at(idx)  获取对应索引处的字符
	// name.substr(start_idx, count)  从idx索引开始,截取count个字符
	// name.find(sub_string)  返回找到的第一个位置的索引,找不到则返回一个很大的数字
	// name.rfind(sub_string) 从右边开始查找,返回第一个的起始索引
	// name.clear() 清空该地址的字符串
	if (name.empty()) { // 字符串为空
		cout << "empty name" << endl;
		goto laufing;
	}
	else if (name.length() < 2) {
		cout << "to short" << endl;
		goto laufing;
	}
	else
	{
		cout << "idx 0:" << name.at(0) << endl;
		cout << "substr:" << name.substr(1, 3) << endl;
		cout << "find:" << name.find("ja") << endl;
		cout << "find:" << name.rfind("ja") << endl;

		name.clear();
		cout << "clear:" << name << endl;
	}
	
	// system("dir");
	system("pause");
	return 0;
}

 

程序调用

  • 源代码打断点,直接在对应的行处点击;再次点击取消断点
    在这里插入图片描述
  • 调试快捷键
    • F5 开始调试,shift+F5 结束调试,Ctrl+F5 直接执行(不调试)
    • F11 逐行执行,shift+F11 到下一个断点;
    • shift+F9 快速监视变量值,选中一个变量->shift+F9,点击‘添加监视’
      在这里插入图片描述
    • 也可以点击菜单栏的‘调试’;

 

综合案例

  • 输入一个自然数 n,判断是否为质数;
    • 只能被1和自身整除,则为质数;
    • 1和自身 不用判断,可以取 2 -> n / 2 之间的值,依次判断是否被n整除;
    • n特别大时,为优化性能,可以取 2 - > sqrt(n)之间的值来判断;
#include <iostream>
using namespace std;

// bool是函数返回值类型
// n是函数的形式参数
bool isPrimer(int n){  //定义一个函数
	int i = 2;
	int upperVal = n / 2;
	// 标志位
	bool flag = true;
	while (i <= upperVal) {
		if(n % i == 0){
			flag = false;
			break;
		}
		++i;
	}
	if (flag) {
		cout << n << "是质数" << endl;
		return 1;
	}
	else {
		cout << n << "不是质数" << endl;
		return 0;
	}
}


int main() {
	
	int n;
	cout << "input a value:" << endl;
	cin >> n;
	isPrimer(n);

	// system("dir");
	system("pause");
	return 0;
}

  • 输入一个自然数n,输出n以内的所有质数;
int i;
for(i=2; i <= n/2; i++){
	if(isPrimer(i))
		cout << i << endl;  // 单行语句,可以省略 { }
	else
		continue;
}

 

  • 猜数字游戏
    • 程序运行时,随机设定一个目标数值;
    • 让用户输入一个数字,与目标数值比较;
    • 大于目标值,则输出‘大了’;
    • 小于目标值,则输出‘小了’;
    • 等于目标值,则输出“恭喜,猜对了”

int main() {
	
	//当前时间戳 秒
	int curTimestamp = time(0);  
	// python中 time.time() 获取时间戳 秒  
	// js: new Date().getTime() 毫秒
	
	
	// 设置随机数种子
	// srand(10); 种子固定,则每次运行程序时,都产生同样的随机数,为了产生不同的随机数
	// 需要设置随机数的种子,即伪随机  --不是真正的随机
	srand(curTimestamp);
	//生成 100 内的随机数
	int target = rand() % 100;  // 1000以内就 %1000
	int guessTimes = 5;
	int curTimes = 1;
	int guessVal;
	while (curTimes <= guessTimes) {
	
		// 让用户输入
		cout << "input your guess:" << endl;
		cin >> guessVal;

		if (guessVal < target) {
			cout << "小了" << endl;
			++curTimes;
		}
		else if (guessVal > target) {
			cout << "大了" << endl;
			++curTimes;
		}
		else {
			cout << "恭喜,猜对了" << endl;
			break;
		}
	
	}
	if (curTimes > guessTimes) {
		cout << "game over" << endl;
	}

	// system("dir");
	system("pause");
	return 0;
}

 
 

下一篇:C++ 教程 - 02 复合数据结构

  • 9
    点赞
  • 7
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

laufing

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值