第一部分:C++是什么?为什么学习它?
1.1 C++简介
C++就像是一种与计算机对话的语言,它:
- 高效快速:直接操作计算机硬件,运行速度快
- 功能强大:可以用来开发游戏、操作系统、科学计算等
- 学习曲线:开始有点难,但掌握后非常强大
1.2 第一个C++程序 - 'Hello World'
#
{
std::cout << << std::endl;
;
}
本文是 C++ 基础语法入门教程,适合零基础学习者。内容涵盖 C++ 简介、变量与数据类型、运算符、控制流程(if-else、循环)、函数定义及数组使用。通过 Hello World 示例引入,详细讲解核心语法规范,并结合 OpenCV 库演示图像处理与运动检测实践,帮助读者建立编程思维并完成基础项目开发。
C++就像是一种与计算机对话的语言,它:
#
{
std::cout << << std::endl;
;
}
逐行解释:
#include <iostream>:告诉编译器'我要用输入输出功能'int main():程序的主入口,就像房子的正门std::cout << "Hello, World!":在屏幕上显示文字return 0;:告诉操作系统'程序运行成功'#include <iostream>
using namespace std;
int main() {
// 定义变量 - 类型 变量名 = 值;
int age = 25; // 整数类型
double height = 1.75; // 小数类型
char grade = 'A'; // 单个字符
string name = "张三"; // 字符串
bool isStudent = true; // 布尔值 (true/false)
// 使用变量
cout << "姓名:" << name << endl;
cout << "年龄:" << age << endl;
cout << "身高:" << height << "米" << endl;
cout << "成绩:" << grade << endl;
cout << "是学生吗?" << isStudent << endl;
return 0;
}
| 类型 | 含义 | 例子 |
|---|---|---|
int | 整数 | 10, -5, 1000 |
double | 小数 | 3.14, -2.5, 0.0 |
char | 字符 | 'A', '1', '#' |
string | 字符串 | "hello", "中文" |
bool | 布尔值 | true, false |
#include <iostream>
using namespace std;
int main() {
int a = 10;
int b = 3;
cout << "a = " << a << ", b = " << b << endl;
cout << "加法:" << a + b << endl; // 13
cout << "减法:" << a - b << endl; // 7
cout << "乘法:" << a * b << endl; // 30
cout << "除法:" << a / b << endl; // 3 (整数除法)
cout << "取余:" << a % b << endl; // 1
// 小数运算
double x = 10.0;
double y = 3.0;
cout << "小数除法:" << x / y << endl; // 3.33333
return 0;
}
#include <iostream>
using namespace std;
int main() {
int a = 10, b = 20;
// 比较运算
cout << "a == b: " << (a == b) << endl; // 相等,输出 0 (false)
cout << "a != b: " << (a != b) << endl; // 不等,输出 1 (true)
cout << "a < b: " << (a < b) << endl; // 小于,输出 1 (true)
cout << "a > b: " << (a > b) << endl; // 大于,输出 0 (false)
// 逻辑运算
bool condition1 = true;
bool condition2 = false;
cout << "条件1 AND 条件2: " << (condition1 && condition2) << endl; // 与运算
cout << "条件1 OR 条件2: " << (condition1 || condition2) << endl; // 或运算
cout << "NOT 条件1: " << (!condition1) << endl; // 非运算
return 0;
}
#include <iostream>
using namespace std;
int main() {
int score;
cout << "请输入你的分数:";
cin >> score; // 从键盘输入
if (score >= 90) {
cout << "优秀!" << endl;
} else if (score >= 80) {
cout << "良好" << endl;
} else if (score >= 60) {
cout << "及格" << endl;
} else {
cout << "不及格,要加油了!" << endl;
}
return 0;
}
#include <iostream>
using namespace std;
int main() {
// 打印 1 到 5
cout << "for循环示例:" << endl;
for (int i = 1; i <= 5; i++) {
cout << "当前数字:" << i << endl;
}
// 计算 1 到 100 的和
int sum = 0;
for (int i = 1; i <= 100; i++) {
sum += i; // 等价于 sum = sum + i;
}
cout << "1到100的和是:" << sum << endl;
return 0;
}
#include <iostream>
using namespace std;
int main() {
// while循环示例
int count = 1;
cout << "while循环示例:" << endl;
while (count <= 5) {
cout << "计数:" << count << endl;
count++; // 重要:不要忘记这个,否则会无限循环!
}
// 用户输入控制循环
int number;
cout << "请输入数字 (输入0退出): ";
cin >> number;
while (number != 0) {
cout << "你输入了:" << number << endl;
cout << "请输入数字 (输入0退出): ";
cin >> number;
}
cout << "程序结束" << endl;
return 0;
}
#include <iostream>
using namespace std;
// 函数定义:返回类型 函数名 (参数)
int add(int a, int b) {
return a + b;
}
// 没有返回值的函数
void printWelcome(string name) {
cout << "欢迎," << name << "!" << endl;
// void 函数不需要 return 语句
}
// 判断是否为偶数的函数
bool isEven(int number) {
return (number % 2 == 0);
}
int main() {
// 使用函数
int result = add(5, 3);
cout << "5 + 3 = " << result << endl;
printWelcome("小明");
int num = 10;
if (isEven(num)) {
cout << num << " 是偶数" << endl;
} else {
cout << num << " 是奇数" << endl;
}
return 0;
}
#include <iostream>
using namespace std;
int main() {
// 定义数组:类型 数组名 [大小]
int scores[5] = {85, 92, 78, 90, 88};
// 访问数组元素(从 0 开始!)
cout << "第一个分数:" << scores[0] << endl;
cout << "第二个分数:" << scores[1] << endl;
// 遍历数组
cout << "所有分数:";
for (int i = 0; i < 5; i++) {
cout << scores[i] << " ";
}
cout << endl;
// 修改数组元素
scores[2] = 95; // 修改第三个元素
// 计算平均分
int total = 0;
for (int i = 0; i < 5; i++) {
total += scores[i];
}
double average = total / 5.0;
cout << "平均分:" << average << endl;
return 0;
}
#include <opencv2/opencv.hpp>
using namespace cv;
using namespace std;
// 这个函数演示了如何用我们学过的 C++ 概念
void explainOpencvCode() {
// 1. 变量定义 - Mat 是 OpenCV 的图像类型
Mat image; // 定义一个图像变量
// 2. 函数调用 - imread 是读取图像的函数
image = imread("test.jpg"); // 调用函数,传递参数"test.jpg"
// 3. 条件判断 - 检查图像是否加载成功
if (image.empty()) {
empty() 返回 bool 值
cout << "无法加载图像!" << endl;
return; // 提前结束函数
}
// 4. 循环 - 处理图像的每个像素
for (int row = 0; row < image.rows; row++) {
// 遍历行
for (int col = 0; col < image.cols; col++) {
// 遍历列
// 获取像素的 BGR 值
Vec3b pixel = image.at<Vec3b>(row, col);
// 修改像素 - 增加红色分量
pixel[2] = min(255, pixel[2] + 50); // [2] 是红色通道
}
}
// 5. 函数调用 - 显示图像
imshow("处理后的图像", image);
waitKey(0); // 等待按键
}
// 简单的运动检测函数(用我们学过的所有概念)
void simpleMotionDetection() {
VideoCapture cap(0); // 创建视频捕获对象
// 条件判断
if (!cap.isOpened()) {
cout << "无法打开摄像头!" << endl;
return;
}
Mat previousFrame, currentFrame;
cap >> previousFrame; // 读取第一帧
// 循环 - 处理视频的每一帧
while (true) {
cap >> currentFrame; // 读取当前帧
// 条件判断
if (currentFrame.empty()) break;
// 转换为灰度图(简化处理)
Mat grayPrevious, grayCurrent;
cvtColor(previousFrame, grayPrevious, COLOR_BGR2GRAY);
cvtColor(currentFrame, grayCurrent, COLOR_BGR2GRAY);
// 计算帧间差异
Mat diff;
absdiff(grayPrevious, grayCurrent, diff);
// 显示结果
imshow("原始视频", currentFrame);
imshow("运动检测", diff);
// 更新前一帧
previousFrame = currentFrame.clone();
// 按键检查
if (waitKey(30) == 27) break; // ESC 键退出
}
}
int main() {
// 调用我们的函数
simpleMotionDetection();
return 0;
}
#include <iostream>
using namespace std;
void commonMistakes() {
// 错误 1: 忘记分号
// int x = 10 // 错误!缺少分号
int x = 10; // 正确
// 错误 2: 使用未初始化的变量
int y;
// cout << y; // 错误!y 没有初始值
y = 20; // 正确:先赋值再使用
// 错误 3: 数组越界
int arr[3] = {1, 2, 3};
// cout << arr[5]; // 错误!访问不存在的元素
// 错误 4: 无限循环
// while (true) { // cout << "无限循环!"; // }
// 错误!没有退出条件
// 正确做法:
int count = 0;
while (count < 5) {
cout << count << " ";
count++;
}
}
// 好的注释习惯
#include <iostream>
using namespace std;
/*
* 这是一个多行注释
* 可以描述函数的功能
*/
int main() {
// 这是单行注释
int number = 10; // 定义并初始化变量
cout << "学习 C++ 就像学走路," << "开始可能会摔倒," << "但坚持下去就能奔跑!" << endl;
return 0;
}

微信公众号「极客日志」,在微信中扫描左侧二维码关注。展示文案:极客日志 zeeklog
使用加密算法(如AES、TripleDES、Rabbit或RC4)加密和解密文本明文。 在线工具,加密/解密文本在线工具,online
生成新的随机RSA私钥和公钥pem证书。 在线工具,RSA密钥对生成器在线工具,online
基于 Mermaid.js 实时预览流程图、时序图等图表,支持源码编辑与即时渲染。 在线工具,Mermaid 预览与可视化编辑在线工具,online
将字符串编码和解码为其 Base64 格式表示形式即可。 在线工具,Base64 字符串编码/解码在线工具,online
将字符串、文件或图像转换为其 Base64 表示形式。 在线工具,Base64 文件转换器在线工具,online
将 Markdown(GFM)转为 HTML 片段,浏览器内 marked 解析;与 HTML 转 Markdown 互为补充。 在线工具,Markdown 转 HTML在线工具,online