C++ 基本语法
概述
C++基本语法是学习C++编程的基础。本章将介绍C++程序的基本结构、语法规则、关键字、标识符等核心概念,为后续深入学习奠定坚实基础。
🏗️ C++ 程序基本结构
最简单的C++程序
cpp
#include <iostream>
int main() {
std::cout << "Hello, World!" << std::endl;
return 0;
}程序结构分析
mermaid
graph TD
A[C++程序] --> B[预处理指令]
A --> C[全局声明]
A --> D[main函数]
A --> E[其他函数]
B --> B1[#include]
B --> B2[#define]
B --> B3[#ifdef]
C --> C1[全局变量]
C --> C2[函数声明]
C --> C3[类声明]
D --> D1[程序入口点]
D --> D2[返回int类型]
E --> E1[用户定义函数]
E --> E2[类成员函数]完整程序示例
cpp
// 预处理指令
#include <iostream>
#include <string>
// 使用命名空间
using namespace std;
// 全局常量
const int MAX_SIZE = 100;
// 函数声明
void greetUser(const string& name);
int calculateSum(int a, int b);
// 主函数
int main() {
// 局部变量
string userName;
int num1, num2;
// 输入
cout << "请输入您的姓名: ";
getline(cin, userName);
cout << "请输入两个数字: ";
cin >> num1 >> num2;
// 函数调用
greetUser(userName);
int result = calculateSum(num1, num2);
// 输出
cout << "计算结果: " << result << endl;
return 0; // 程序正常结束
}
// 函数定义
void greetUser(const string& name) {
cout << "你好, " << name << "!" << endl;
}
int calculateSum(int a, int b) {
return a + b;
}📝 词法元素
标识符 (Identifiers)
标识符规则
cpp
// 有效的标识符
int age; // 字母开头
int user_age; // 下划线分隔
int userAge; // 驼峰命名
int _private; // 下划线开头
int value2; // 包含数字
// 无效的标识符
// int 2value; // 数字开头 ❌
// int user-age; // 包含连字符 ❌
// int class; // 关键字 ❌
// int user age; // 包含空格 ❌命名约定
cpp
// 变量和函数:小写字母开头,驼峰命名
int studentAge;
string firstName;
void calculateTotal();
// 常量:全大写,下划线分隔
const int MAX_STUDENTS = 50;
const double PI = 3.14159;
// 类名:大写字母开头,驼峰命名
class StudentRecord;
class BankAccount;
// 私有成员:下划线结尾或开头
class MyClass {
private:
int value_;
string _name;
};关键字 (Keywords)
C++关键字列表
cpp
// C++98关键字
alignas alignof and and_eq asm
auto bitand bitor bool break
case catch char char16_t char32_t
class compl const constexpr const_cast
continue decltype default delete do
double dynamic_cast else enum explicit
export extern false float for
friend goto if inline int
long mutable namespace new noexcept
not not_eq nullptr operator or
or_eq private protected public register
reinterpret_cast return short signed
sizeof static static_assert static_cast struct
switch template this thread_local throw
true try typedef typeid typename
union unsigned using virtual void
volatile wchar_t while xor xor_eq
// C++11及以后新增的关键字
// auto (重新定义)
// decltype
// nullptr
// constexpr
// static_assert
// thread_local
// alignas
// alignof
// char16_t
// char32_t
// noexcept关键字使用示例
cpp
// 数据类型关键字
bool isValid = true;
char letter = 'A';
int number = 42;
float price = 19.99f;
double precision = 3.14159;
// 控制流关键字
if (isValid) {
// 条件执行
} else {
// 替代执行
}
for (int i = 0; i < 10; ++i) {
// 循环执行
if (i == 5) break; // 跳出循环
if (i % 2 == 0) continue; // 跳过本次迭代
}
// 面向对象关键字
class Base {
public:
virtual void method() {}
protected:
int protectedValue;
private:
int privateValue;
};
class Derived : public Base {
public:
void method() override {} // C++11
};🔤 字面量 (Literals)
数值字面量
cpp
// 整数字面量
int decimal = 42; // 十进制
int octal = 052; // 八进制 (以0开头)
int hexadecimal = 0x2A; // 十六进制 (以0x开头)
int binary = 0b101010; // 二进制 (C++14, 以0b开头)
// 长整数字面量
long longValue = 42L; // long
long long veryLong = 42LL; // long long
unsigned int unsignedVal = 42U; // unsigned
// 浮点数字面量
float floatValue = 3.14f; // float (f后缀)
double doubleValue = 3.14; // double (默认)
long double longDouble = 3.14L; // long double (L后缀)
// 科学计数法
double scientific = 1.23e4; // 1.23 × 10^4 = 12300
double negative = 1.23e-4; // 1.23 × 10^-4 = 0.000123
// C++14数字分隔符
int million = 1'000'000;
double pi = 3.141'592'653;字符和字符串字面量
cpp
// 字符字面量
char ch = 'A'; // 普通字符
char newline = '\n'; // 转义字符
char tab = '\t'; // 制表符
char backslash = '\\'; // 反斜杠
char quote = '\''; // 单引号
// 特殊字符
char null_char = '\0'; // 空字符
char bell = '\a'; // 响铃
char backspace = '\b'; // 退格
char carriage_return = '\r'; // 回车
// 数值表示的字符
char ascii_A = 65; // ASCII码
char hex_A = '\x41'; // 十六进制
char octal_A = '\101'; // 八进制
// 字符串字面量
string simple = "Hello";
string with_escapes = "Hello\nWorld";
string with_quote = "She said \"Hello\"";
// 原始字符串 (C++11)
string raw = R"(C:\Users\Name\Documents)";
string multi_line = R"(
This is a
multi-line
string
)";
// 宽字符和Unicode (C++11)
wchar_t wide_char = L'中';
string utf8 = u8"UTF-8 字符串";
u16string utf16 = u"UTF-16 字符串";
u32string utf32 = U"UTF-32 字符串";布尔和指针字面量
cpp
// 布尔字面量
bool isTrue = true;
bool isFalse = false;
// 空指针字面量 (C++11)
int* ptr = nullptr; // 推荐方式
int* old_ptr = NULL; // 传统方式 (不推荐)
int* zero_ptr = 0; // 整数0 (不推荐)🎯 运算符基础
算术运算符
cpp
int a = 10, b = 3;
// 基本算术运算
int sum = a + b; // 加法: 13
int diff = a - b; // 减法: 7
int product = a * b; // 乘法: 30
int quotient = a / b; // 整数除法: 3
int remainder = a % b; // 取余: 1
// 浮点除法
double precise_div = static_cast<double>(a) / b; // 3.33333...
// 自增自减运算符
int x = 5;
int pre_inc = ++x; // 前置自增: x=6, pre_inc=6
int post_inc = x++; // 后置自增: post_inc=6, x=7
int y = 5;
int pre_dec = --y; // 前置自减: y=4, pre_dec=4
int post_dec = y--; // 后置自减: post_dec=4, y=3赋值运算符
cpp
int x = 10;
// 复合赋值运算符
x += 5; // x = x + 5; 结果: x = 15
x -= 3; // x = x - 3; 结果: x = 12
x *= 2; // x = x * 2; 结果: x = 24
x /= 4; // x = x / 4; 结果: x = 6
x %= 4; // x = x % 4; 结果: x = 2
// 位运算复合赋值
x |= 8; // x = x | 8; 按位或
x &= 15; // x = x & 15; 按位与
x ^= 5; // x = x ^ 5; 按位异或
x <<= 1; // x = x << 1; 左移
x >>= 1; // x = x >> 1; 右移比较运算符
cpp
int a = 10, b = 20;
// 相等性比较
bool equal = (a == b); // false
bool not_equal = (a != b); // true
// 关系比较
bool less = (a < b); // true
bool greater = (a > b); // false
bool less_equal = (a <= b); // true
bool greater_equal = (a >= b); // false
// 字符串比较
string str1 = "apple";
string str2 = "banana";
bool str_less = (str1 < str2); // true (字典序)逻辑运算符
cpp
bool p = true, q = false;
// 逻辑运算
bool and_result = p && q; // 逻辑与: false
bool or_result = p || q; // 逻辑或: true
bool not_result = !p; // 逻辑非: false
// 短路求值
bool short_circuit = false && (1/0 == 1); // 不会执行除零操作
// 复杂逻辑表达式
int age = 25;
bool isAdult = (age >= 18) && (age <= 65);
bool canVote = (age >= 18) || (age == 17 && hasPermission);🔧 语句类型
表达式语句
cpp
// 简单表达式语句
int x; // 声明语句
x = 42; // 赋值语句
++x; // 自增语句
calculateSum(a, b); // 函数调用语句
// 复合表达式
x = y = z = 0; // 连续赋值
result = (x + y) * z; // 算术表达式复合语句 (代码块)
cpp
{
// 代码块创建新的作用域
int localVar = 10;
{
// 嵌套代码块
int innerVar = 20;
localVar += innerVar; // 可以访问外层变量
}
// innerVar在这里不可访问
}
// localVar在这里也不可访问条件语句
cpp
// if语句
if (condition) {
// 条件为真时执行
}
// if-else语句
if (condition) {
// 条件为真
} else {
// 条件为假
}
// if-else if-else语句
if (score >= 90) {
grade = 'A';
} else if (score >= 80) {
grade = 'B';
} else if (score >= 70) {
grade = 'C';
} else {
grade = 'F';
}
// C++17 if语句初始化器
if (auto result = calculate(); result > 0) {
cout << "Positive result: " << result << endl;
}循环语句
cpp
// for循环
for (int i = 0; i < 10; ++i) {
cout << i << " ";
}
// while循环
int count = 0;
while (count < 5) {
cout << count << endl;
++count;
}
// do-while循环
int input;
do {
cout << "Enter a positive number: ";
cin >> input;
} while (input <= 0);
// 范围based for循环 (C++11)
vector<int> numbers = {1, 2, 3, 4, 5};
for (const auto& num : numbers) {
cout << num << " ";
}跳转语句
cpp
// break语句
for (int i = 0; i < 10; ++i) {
if (i == 5) {
break; // 跳出循环
}
cout << i << " ";
}
// continue语句
for (int i = 0; i < 10; ++i) {
if (i % 2 == 0) {
continue; // 跳过偶数
}
cout << i << " "; // 只打印奇数
}
// return语句
int findMax(int a, int b) {
if (a > b) {
return a; // 返回较大值
}
return b;
}
// goto语句 (不推荐使用)
for (int i = 0; i < 10; ++i) {
for (int j = 0; j < 10; ++j) {
if (condition) {
goto cleanup; // 跳出嵌套循环
}
}
}
cleanup:
// 清理代码🎨 代码风格和格式
缩进和空格
cpp
// 推荐的缩进风格
class MyClass {
public: // 访问修饰符不缩进或缩进1个单位
void method() { // 方法缩进
if (condition) { // 语句缩进
doSomething(); // 嵌套语句进一步缩进
}
}
private:
int memberVariable_; // 成员变量缩进
};
// 运算符周围的空格
int result = a + b * c; // 推荐
int result=a+b*c; // 不推荐
// 逗号后的空格
function(arg1, arg2, arg3); // 推荐
function(arg1,arg2,arg3); // 不推荐大括号风格
cpp
// K&R风格 (推荐)
if (condition) {
doSomething();
} else {
doSomethingElse();
}
// Allman风格
if (condition)
{
doSomething();
}
else
{
doSomethingElse();
}
// 单行语句的大括号
if (condition) {
doSomething(); // 即使单行也建议使用大括号
}
// 不推荐
if (condition)
doSomething(); // 容易引入错误命名约定
cpp
// 变量和函数:小驼峰
int studentAge;
string firstName;
void calculateTotal();
// 常量:全大写下划线分隔
const int MAX_SIZE = 100;
const double PI = 3.14159;
// 类和结构体:大驼峰
class StudentRecord {
public:
void printInfo();
private:
string studentName_; // 私有成员后缀下划线
int studentId_;
};
// 枚举:大驼峰或全大写
enum class Color {
Red,
Green,
Blue
};
enum Status {
STATUS_READY,
STATUS_RUNNING,
STATUS_STOPPED
};💡 最佳实践
1. 初始化变量
cpp
// 推荐:声明时初始化
int count = 0;
string name = "";
vector<int> numbers{1, 2, 3};
// 不推荐:未初始化
int count; // 可能包含垃圾值
string name; // 虽然string会自动初始化为空2. 使用const
cpp
// 对不会修改的变量使用const
const int MAX_ATTEMPTS = 3;
const string CONFIG_FILE = "config.ini";
// 函数参数使用const引用
void printStudent(const Student& student) {
cout << student.getName() << endl;
}
// const成员函数
class Point {
public:
int getX() const { return x_; } // 不修改对象状态
void setX(int x) { x_ = x; } // 修改对象状态
private:
int x_, y_;
};3. 避免全局变量
cpp
// 不推荐:全局变量
int globalCounter = 0;
void incrementCounter() {
++globalCounter; // 难以追踪修改
}
// 推荐:局部变量或类成员
class Counter {
public:
void increment() { ++count_; }
int getCount() const { return count_; }
private:
int count_ = 0;
};4. 使用现代C++特性
cpp
// 使用auto进行类型推导
auto numbers = vector<int>{1, 2, 3, 4, 5};
auto it = numbers.begin();
// 使用范围for循环
for (const auto& num : numbers) {
cout << num << " ";
}
// 使用nullptr而不是NULL
int* ptr = nullptr; // 推荐
int* old_ptr = NULL; // 不推荐
// 使用大括号初始化
int x{42}; // 推荐,防止窄化转换
int y = 42; // 传统方式5. 错误处理
cpp
// 检查输入参数
int divide(int numerator, int denominator) {
if (denominator == 0) {
throw invalid_argument("除数不能为零");
}
return numerator / denominator;
}
// 检查函数返回值
ifstream file("data.txt");
if (!file.is_open()) {
cerr << "无法打开文件" << endl;
return -1;
}🔍 调试技巧
编译器警告
cpp
// 启用所有警告进行编译
// g++ -Wall -Wextra -pedantic -std=c++17 main.cpp
// 示例:可能的警告
int main() {
int unused_variable = 42; // 警告:未使用的变量
for (int i = 0; i < 10; ++i) {
// 空循环体可能触发警告
}
// 缺少return语句的警告
}调试输出
cpp
#include <iostream>
#include <cassert>
// 调试宏
#ifdef DEBUG
#define DBG_PRINT(x) std::cout << "DEBUG: " << x << std::endl
#else
#define DBG_PRINT(x)
#endif
int main() {
int value = 42;
DBG_PRINT("Value is: " << value);
// 使用断言检查假设
assert(value > 0 && "Value should be positive");
return 0;
}总结
本章介绍了C++的基本语法要素:
核心概念
- 程序结构:预处理指令、声明、main函数
- 词法元素:标识符、关键字、字面量
- 运算符:算术、赋值、比较、逻辑运算符
- 语句类型:表达式、复合、条件、循环、跳转语句
编程规范
- 一致的命名约定
- 适当的代码格式和缩进
- 合理使用const和现代C++特性
- 良好的错误处理习惯
最佳实践
- 声明时初始化变量
- 避免全局变量
- 使用现代C++特性提高代码质量
- 启用编译器警告帮助发现问题
掌握这些基本语法是后续学习C++高级特性的基础。在接下来的章节中,我们将深入学习C++的数据类型、变量、函数等更具体的概念。