C++ 是一种静态类型、编译型的多范式编程语言,兼容 C 语言的同时,进一步引入了面向对象编程(OOP)和泛型编程等高级特性。因其高效性和灵活性,被广泛应用于系统软件开发、游戏引擎、嵌入式系统以及高性能计算等领域。本文将从核心概念出发,帮助你快速掌握 C++ 的入门要点。
二、基本语法要素
1. 变量与数据类型
C++ 属于静态类型语言,所有变量在使用前必须声明其类型。常见的基础数据类型包括:
| 类型 | 说明 | 示例 |
|---|---|---|
int |
整型(通常为4字节,默认有符号) | int a = 10; |
float |
单精度浮点型(4字节) | float f = 3.14f; |
double |
双精度浮点型(8字节) | double d = 3.14159; |
char |
字符型(1字节) | char c = 'A'; |
bool |
布尔型,取值 true 或 false | bool flag = true; |
void |
无类型,常用于函数返回类型或指针定义 | - |
变量命名需遵循以下规则:由字母、数字和下划线组成,不能以数字开头,且区分大小写。还可配合修饰符增强语义:
unsigned:表示无符号整数;const:定义常量,不可修改;long/short:用于扩展或缩短整型长度。
int
int age = 18;
float
float pi = 3.14f;
double
double pi = 3.1415926;
char
char ch = 'A';
bool
bool flag = true;
void
unsigned
const
long
short
int main() {
int num = 100;
const double PI = 3.14159;
unsigned int count = 50;
return 0;
}
const double PI = 3.14159; // 常量,值不可改
unsigned int num = 100; // 无符号整型,只能存非负数
2. 运算符
C++ 支持多种运算符,主要包括算术、赋值、比较、逻辑及位运算等,与 C 语言基本一致。
int a = 10, b = 3;
cout << (a + b) << endl; // 加法
cout << (a > b) << endl; // 比较
cout << (a & b) << endl; // 位与
// 算术运算符:+ - * / %(取模)
int a = 10, b = 3;
cout << a / b << endl; // 3(整数除法)
cout << (double)a / b; // 3.33333(强制类型转换)
// 赋值运算符:= += -= *= /=
a += 5; // 等价于 a = a + 5
// 比较运算符:== != > < >= <=
bool res = (a > b); // true
// 逻辑运算符:&&(与) ||(或) !(非)
if (a > 5 && b < 5) { /* 执行逻辑 */ }
3. 控制流
控制程序执行流程是编程的基础,主要包括条件判断、循环和跳转语句。
(1)条件语句
if (score >= 90) {
cout << "优秀" << endl;
} else if (score >= 60) {
cout << "及格" << endl;
} else {
cout << "不及格" << endl;
}
// if-else
int score = 85;
if (score >= 90) {
cout << "优秀" << endl;
} else if (score >= 80) {
cout << "良好" << endl;
} else {
cout << "及格" << endl;
}
// switch(匹配整型/字符型/枚举)
char grade = 'B';
switch (grade) {
case 'A': cout << "90+"; break; // break 防止穿透
case 'B': cout << "80-89"; break;
default: cout << "其他";
}
(2)循环语句
for (int i = 0; i < 5; ++i) {
cout << i << " ";
}
int j = 0;
while (j < 5) {
cout << j++ << " ";
}
// for 循环(已知次数)
for (int i = 0; i < 5; i++) {
cout << i << " "; // 输出 0 1 2 3 4
}
// while 循环(未知次数,先判断后执行)
int n = 10;
while (n > 0) {
cout << n-- << " "; // 输出 10 9 ... 1
}
// do-while(至少执行一次)
int m = 0;
do {
cout << m++;
} while (m < 3); // 输出 012
(3)跳转语句
break:终止当前循环或 switch 结构;continue:跳过本次循环剩余部分,进入下一轮迭代;return:结束函数并返回指定值。
break
continue
return
三、函数
函数是实现代码复用的重要手段。相比 C 语言,C++ 提供了更多灵活性,如函数重载和默认参数等功能。
1. 函数基本结构
int add(int a, int b) {
return a + b;
}
// 函数声明(原型):返回值类型 函数名(参数列表);
int add(int x, int y);
// 函数定义:实现逻辑
int add(int x, int y) {
return x + y; // 返回值
}
// 函数调用
int main() {
int sum = add(3, 5); // sum = 8
cout << sum << endl;
return 0;
}
2. 函数重载(C++ 特性)
在同一作用域中,允许存在多个同名函数,只要它们的参数列表不同(数量、类型或顺序),即构成重载。
int max(int a, int b);
double max(double a, double b);
string max(string a, string b);
// 重载1:两个int相加
int add(int a, int b) { return a + b; }
// 重载2:三个int相加
int add(int a, int b, int c) { return a + b + c; }
// 重载3:两个double相加
double add(double a, double b) { return a + b; }
int main() {
cout << add(1,2) << endl; // 调用第一个
cout << add(1,2,3) << endl; // 调用第二个
cout << add(1.5, 2.5) << endl;// 调用第三个
return 0;
}
3. 默认参数
函数参数可以设置默认值,调用时可省略该参数。注意:默认参数应从右向左依次设定。
void greet(string name, string prefix = "Hello") {
cout << prefix << ", " << name << endl;
}
// 调用:greet("Alice"); 输出 Hello, Alice
// 默认参数:y默认值为10
int add(int x, int y = 10) {
return x + y;
}
int main() {
cout << add(5) << endl; // 5+10=15
cout << add(5, 20) << endl; // 5+20=25
return 0;
}
四、数组与字符串
1. 数组
数组用于存储相同类型的固定长度数据序列。
int arr[5] = {1, 2, 3, 4, 5};
for (int i = 0; i < 5; ++i) {
cout << arr[i] << " ";
}
// 数组声明:类型 数组名[长度];
int arr[5] = {1,2,3,4,5}; // 初始化
int arr2[] = {6,7,8}; // 长度自动推导为3
// 访问数组元素(下标从0开始)
cout << arr[2] << endl; // 3
// 遍历数组
for (int i = 0; i < sizeof(arr)/sizeof(arr[0]); i++) {
cout << arr[i] << " ";
}
2. 字符串
C++ 中有两种主要的字符串表示方式:
(1)C 风格字符串(字符数组)
以空字符 '\0' 结尾的字符数组。
char str[] = "Hello";
cout << str << endl;
char str[] = "hello";
cout << strlen(str) << endl; // 长度5(不含结束符'\0')
(2)C++ 标准字符串(std::string,推荐使用)
封装良好的字符串类,操作更安全便捷。
#include <string>
string s = "Welcome!";
s += " to C++";
cout << s << endl;
std::string
#include <string> // 需包含头文件
string s1 = "hello";
string s2 = " world";
string s3 = s1 + s2; // 拼接:"hello world"
// 常用操作
cout << s3.length() << endl; // 长度11
cout << s3.substr(0,5) << endl; // 子串:"hello"
s3.append("!"); // 追加:"hello world!"
五、指针与引用(C++ 核心机制)
1. 指针
指针是一种变量,用于保存另一个变量的内存地址。声明形式为:数据类型* 变量名;
int x = 10;
int* ptr = &x;
cout << *ptr << endl; // 输出 10
类型* 指针名;
int num = 10;
int* p = # // &取地址,p指向num的地址
cout << *p << endl; // *解引用,输出10
*p = 20; // 修改指针指向的变量值,num变为20
// 空指针
int* p_null = nullptr; // C++11 推荐(替代NULL)
2. 引用
引用是某个已存在变量的别名,声明格式为:数据类型& 引用名 = 原变量;。引用必须初始化,且一旦绑定后不能更改指向。
int y = 20;
int& ref = y;
ref = 30; // 相当于 y = 30
类型& 引用名 = 变量;
int a = 10;
int& ref = a; // ref是a的别名
ref = 20; // a变为20
cout << a << endl; // 20
// 引用常用于函数参数(避免拷贝,可修改原变量)
void swap(int& x, int& y) {
int temp = x;
x = y;
y = temp;
}
int main() {
int m = 5, n = 10;
swap(m, n); // m=10, n=5
return 0;
}
六、面向对象基础(OOP)
面向对象是 C++ 的核心特性之一,主要包括类、对象、封装、继承和多态五大概念。
1. 类与对象
类是一种用户自定义的数据类型,包含成员变量(属性)和成员函数(行为)。
class Student {
public:
string name;
void study() {
cout << name << " is studying." << endl;
}
};
Student s;
s.name = "Tom";
s.study();
// 类定义
class Person {
private: // 私有(仅类内可访问,默认私有)
string name;
int age;
public: // 公有(外部可访问)
// 构造函数(创建对象时初始化)
Person(string n, int a) : name(n), age(a) {}
// 成员函数
void showInfo() {
cout << "姓名:" << name << ",年龄:" << age << endl;
}
// 设置/获取私有成员(封装)
void setAge(int a) {
if (a > 0) age = a; // 合法性校验
}
};
// 创建对象(实例化)
int main() {
Person p1("张三", 20);
p1.showInfo(); // 输出:姓名:张三,年龄:20
p1.setAge(21);
p1.showInfo(); // 输出:姓名:张三,年龄:21
return 0;
}
2. 继承
通过继承,子类可以获得父类的成员,从而实现代码复用。
class Person {
public:
void speak() { cout << "Speaking..." << endl; }
};
class Student : public Person {
// 自动拥有 speak() 方法
};
// 子类 Student 继承 Person
class Student : public Person {
private:
int score;
public:
// 构造函数:调用父类构造
Student(string n, int a, int s) : Person(n, a), score(s) {}
void showStudentInfo() {
showInfo(); // 调用父类方法
cout << "成绩:" << score << endl;
}
};
int main() {
Student s("李四", 18, 90);
s.showStudentInfo();
return 0;
}
七、常用标准库组件
C++ 标准模板库(STL)提供了大量高效的工具组件,初学者应熟悉以下几个关键头文件:
<iostream>:负责输入输出操作;<string>:支持 std::string 字符串处理;<vector>:提供动态数组功能,优于传统数组;<algorithm>:包含排序、查找等通用算法。
<iostream>
<string>
<vector>
<algorithm>
示例:使用 vector 和 sort 进行排序
#include <vector>
#include <algorithm>
vector<int> nums = {5, 2, 8, 1};
sort(nums.begin(), nums.end());
#include <vector>
#include <algorithm>
int main() {
vector<int> vec = {5,2,8,1};
sort(vec.begin(), vec.end()); // 排序:1,2,5,8
for (int num : vec) { // 范围for循环(C++11)
cout << num << " ";
}
return 0;
}
一、第一个 C++ 程序:Hello World
从经典的“Hello World”程序开始,了解 C++ 程序的基本结构。
#include <iostream>
using namespace std;
int main() {
cout << "Hello, World!" << endl;
return 0;
}
// 包含输入输出流头文件(C++ 标准库)
#include <iostream>
// 使用 std 命名空间(避免重复写 std::)
using namespace std;
// 主函数:程序入口,返回值为int类型
int main() {
// 输出字符串到控制台,endl 表示换行并刷新缓冲区
cout << "Hello, C++ World!" << endl;
// 返回 0 表示程序正常结束
return 0;
}
关键说明:
头文件:
#include <iostream> 引入标准输入输出流库。C++ 标准库头文件不带 .h 后缀;而 C 语言风格的头文件如 <stdio.h> 也可使用,但推荐使用 C++ 版本,例如 <cstdio>。
#include <iostream>
.h
<stdio.h>
<cstdio>
命名空间:
std 是 C++ 标准库所使用的命名空间。using namespace std; 表示可以直接使用其中的标识符(如 cout、endl)。若避免潜在命名冲突,也可采用显式调用方式,如 std::cout。
std
using namespace std;
cout
endl
std::cout
主函数:
int main() 是每个 C++ 程序的唯一入口点,必须存在且仅有一个。返回类型为 int,代表程序退出状态(C++11 起可省略 return 0;,编译器会自动补全)。
main()
int
return 0
编译运行命令:
Windows(使用 MinGW/GCC):
g++ hello.cpp -o hello.exe
hello.exe
g++ hello.cpp -o hello.exe && hello.exe
Linux / Mac:
g++ hello.cpp -o hello
./hello
g++ hello.cpp -o hello && ./hello
八、学习建议
- 动手实践:每学习一个知识点,立即编写代码进行验证,比如修改循环条件、尝试函数重载等。
- 从小项目入手:通过实现简易计算器、猜数字游戏或学生成绩管理系统来巩固知识。
- 理解内存模型:重点掌握指针、引用的区别,以及栈与堆的使用场景,预防内存泄漏和非法访问等问题。
- 循序渐进:先扎实掌握基础语法,再逐步深入学习面向对象、STL 容器、模板编程和异常处理等进阶内容。


雷达卡


京公网安备 11010802022788号







