C 与 C++ 学习笔记:语法、运算符优先级与进阶

一、C 语言入门:Hello World

// hello_world.c
#include <stdio.h>
int main() {
    printf("Hello, World!\n");
    return 0;
}
gcc hello_world.c -o hello_world
./hello_world   # Out: Hello, World!

二、C 核心语法要点

文件 I/O(高级访问)——#include <stdio.h>

  • FILE* fopen(char *name, char *mode):mode 为 r (读)/w (写)/a (追加),失败返回 NULL
  • 三个标准指针:stdin、stdout、stderr
  • getc/putc、fprintf/fscanf、fgets/fputs、remove、rename、tmpfile、fclose

错误处理:ferror()、feof()(EOF 时非零)、perror()

底层访问(文件描述符)——#include <fcntl.h>、#include <unistd.h>

  • open/close/read/write/lseek/unlink/create
  • 标准描述符:0 = 标准输入、1 = 标准输出、2 = 标准错误

结构体 struct:定义后用 . 访问(结构变量)或 -> 访问(结构指针)

struct packet { int size; double length; double breadth; };
struct packet *p = malloc(sizeof(struct packet));
p->size = 100;

联合体 union:所有字段共享同一内存地址(同一起始地址)

union S { uint32_t w; uint16_t hw; uint8_t b; };

注意小端机器上字节序会反转显示。

枚举 enum:默认从 0 递增,可当普通变量和常量使用。

位域:用于把多个变量打包进一个机器字节,类型必须为 unsigned int,用 : 指定位长

struct flags {
    unsigned int is_color:1;
    unsigned int is_sound:1;
    unsigned int status:4;
};

typedef 别名:typedef double dist_t; 之后可用 dist_t 代替 double。

三、C/C++ 运算符优先级(16 级,从高到低)

  1. 顶级(成员与后缀):() [] -> . 后缀 ++/--
  2. 单目(右结合):前缀 ++/-- ! ~ * & (type) sizeof new/delete
  3. 算术:* / % → + -
  4. 位移与关系:<< >> → < <= > >= → == !=(关系高于位运算,此处最易错)
  5. 位运算:& > ^ > |(按位与 > 异或 > 或)
  6. 逻辑运算(短路):&& > ||;! 是单目已在上层
  7. 条件:?:
  8. 赋值:= += 等(右结合)
  9. 逗号:,(最低)

记法:优先级高的先算,拿不准就用括号,永远比背优先级更可靠。

四、C++ 入门:Hello World

// hello_world.cpp
#include <iostream>
using namespace std;
int main() {
    cout << "Hello, World!" << endl;
    return 0;
}
sudo yum install gcc-c++
g++ hello_world.cpp -o hello_world
./hello_world   # Out: Hello, World!

五、C++ 进阶方向与资源框架

从 C++学习 原篇提炼的进阶主线:

  • 模板编程:C++ 模板、模板元编程、特化与偏特化
  • 经典书籍:《C++ 模板元编程》《C++ 设计新思维 —— 泛型编程与设计模式之应用》《深入理解 C++…》
  • 核心主题:Policy-Based Class Design、Typelist、泛化仿函数、Singleton、Smart Pointers、Object/Abstract Factory、Visitor、MultiMethods
  • 参考:菜鸟教程 C++ 模板、awesome-cpp、C++ Template 教学指南

发表评论

您的邮箱地址不会被公开。 必填项已用 * 标注

滚动至顶部