#include <stdio.h> // 头文件包含
int Hmifun() { // 函数入口
printf("Hello, World!\n");
return 0; // 返回值
}
#include <iostream> // C++ 标准库头文件
using namespace std; // 命名空间
int Hmifun() {
cout << "Hello, World!" << endl; // 输出
return 0;
}
变量与数据类型
整型:int, short, long, char
浮点型:float, double
布尔型(C++):bool
无符号类型:unsigned int 等
int num = 10;
double pi = 3.14;
char c = 'A';
算术:+, -, *, /, %
关系:==, !=, >, <
逻辑:&& (与), || (或), ! (非)
位运算:&, |, ^, <<, >>
赋值:=, +=, -= 等
if (a > b) {
// 代码块
} else if (a == b) {
// 代码块
} else {
// 代码块
}
// for 循环
for (int i = 0; i < 10; i++) {
// 代码块
}
// while 循环
while (condition) {
// 代码块
}
// do-while 循环
do {
// 代码块
} while (condition);
int add(int a, int b) { // 定义函数
return a + b;
}
int result = add(3, 4); // 调用函数
函数重载(同名函数,参数不同):
int add(int a, int b) { return a + b; }
double add(double a, double b) { return a + b; }
int num = 10;
int *ptr = # // ptr 指向 num 的地址
*ptr = 20; // 通过指针修改值
int num = 10;
int &ref = num; // ref 是 num 的别名
ref = 20; // 修改 ref 等同于修改 num
int arr[5] = {1, 2, 3, 4, 5};
arr[0] = 10; // 访问第一个元素
char str[] = "Hello"; // 以 '\0' 结尾
#include <string>
string s = "Hello";
struct Point {
int x;
int y;
};
struct Point p1 = {1, 2};
class Rectangle {
private:
int width, height;
public:
Rectangle(int w, int h) : width(w), height(h) {}
int area() { return width * height; }
};
Rectangle rect(3, 4);
int a = rect.area();
int *arr = (int*)malloc(10 * sizeof(int));
free(arr);
int *arr = new int[10];
delete[] arr;
FILE *file = fopen("test.txt", "r");
char buffer[100];
fgets(buffer, 100, file);
fclose(file);
#include <fstream>
ifstream in("test.txt");
string line;
getline(in, line);
in.close();
template <typename T>
T max(T a, T b) { return (a > b) ? a : b; }
try { throw "Error"; }
catch (const char* msg) { cout << msg; }
指针与内存泄漏:动态分配的内存需手动释放。
作用域:变量的生命周期(局部变量 vs 全局变量)。
#ifndef HEADER_H
#define HEADER_H
// 头文件内容
#endif