C++ 基本语法


C++ 基本语法的简明教程,适合快速入门:

一、C++ 程序基本结构

#include  // 头文件包含
using namespace std; // 使用标准命名空间

int main() { // 主函数,程序入口
    cout << "Hello, World!" << endl; // 输出语句
    return 0; // 返回值
}

二、注释

// 单行注释

/*
   多行注释
   可以跨多行
*/

三、变量与数据类型

1. 基本数据类型

类型 说明 示例
int 整型 int age = 20
float 单精度浮点型 float pi = 3.14f
double 双精度浮点型 double price = 9.99
char 字符型 char c = 'A'
bool 布尔型(true/false) bool isOpen = true
string 字符串(需包含头文件 ``) string name = "Alice"

2. 变量声明与初始化

int a = 5;      // 直接初始化
int b(10);      // 构造函数式初始化
int c{15};      // 统一初始化(C++11)
auto d = 3.14;  // 自动类型推断(C++11)

四、运算符

// 算术运算符
int sum = a + b;
int mod = a % 3; // 取余

// 关系运算符
bool isEqual = (a == b); // ==, !=, >, <, >=, <=

// 逻辑运算符
bool result = (a > 0) && (b < 10); // &&(与), ||(或), !(非)

五、输入输出

int num;
cout << "Enter a number: "; // 输出提示
cin >> num;                 // 读取输入
cout << "You entered: " << num << endl;

六、控制结构

1. 条件语句

if (score >= 90) {
    cout << "A" << endl;
} else if (score >= 60) {
    cout << "Pass" << endl;
} else {
    cout << "Fail" << endl;
}

// switch语句
switch (grade) {
    case 'A': cout << "Excellent"; break;
    case 'B': cout << "Good"; break;
    default: cout << "Invalid";
}

2. 循环语句

// for循环
for (int i = 0; i < 5; i++) {
    cout << i << " ";
}

// while循环
int i = 0;
while (i < 5) {
    cout << i << " ";
    i++;
}

// do-while循环
int j = 0;
do {
    cout << j << " ";
    j++;
} while (j < 5);

七、数组

int arr1[3] = {10, 20, 30}; // 一维数组
int arr2[2][3] = {{1,2,3}, {4,5,6}}; // 二维数组

// 字符串(字符数组)
char str[] = "Hello";
string s = "C++"; // 使用 string 类更安全

八、函数

// 函数定义
int add(int x, int y) {
    return x + y;
}

// 函数调用
int result = add(3, 4);

// 参数传递方式
void swap(int &a, int &b) { // 引用传递
    int temp = a;
    a = b;
    b = temp;
}

九、指针与引用

int num = 10;
int *p = #  // 指针指向 num 的地址
cout << *p;     // 输出 10(解引用)

int &ref = num; // 引用是变量的别名
ref = 20;       // num 变为 20

十、结构体

struct Student {
    string name;
    int age;
    float score;
};

// 使用结构体
Student stu1;
stu1.name = "Bob";
stu1.age = 18;

十一、类与对象(面向对象基础)

class Person {
private:
    string name; // 私有成员
public:
    // 构造函数
    Person(string n) : name(n) {}

    // 成员函数
    void sayHello() {
        cout << "Hello, I'm " << name << endl;
    }
};

// 创建对象
Person p("Alice");
p.sayHello();

十二、标准库常用工具

#include 
#include 

vector nums = {1, 2, 3}; // 动态数组
nums.push_back(4);            // 添加元素

string s = "Hello";
s += " C++";                  // 字符串拼接

综合示例:简单学生管理系统

#include 
#include 
using namespace std;

struct Student {
    string name;
    int score;
};

void addStudent(vector &students) {
    Student s;
    cout << "Enter name: ";
    cin >> s.name;
    cout << "Enter score: ";
    cin >> s.score;
    students.push_back(s);
}

int main() {
    vector students;
    addStudent(students);
    cout << "Students count: " << students.size() << endl;
    return 0;
}

以上内容覆盖了 C++ 最基础的语法,建议通过实际编码练习巩固。进一步学习可深入面向对象、模板、STL 等高级主题。