文件
Paze-C-CPP-Compiler/docs/cpp-plan.md
T
Paze AI d4b6fdc1f3 feat: C++ 阶段 2 - 运算符重载支持
- 成员运算符: Class::operator+ -> Cls_add (类内定义 + 外部定义)
- 自由运算符: Vec operator+(Vec a, Vec b) -> Cls_add(struct Cls *this, struct Cls b)
  首参重写为 this, 函数体内引用重写 (a.x -> this->x)
- 表达式转换: var = a op b -> var = Cls_op(&a, b); var1 op var2 -> Cls_op(&v1, v2)
- 修复: struct 类路由到 parse_class (消除 T_STRUCT 逐字复制死循环)
- 修复: 局部类变量 Complex r; 非破坏性 peek (read_tok 重写)
- 修复: 多声明符 Cls a, b; 记录所有变量
- 修复: 无 ctor 类的运算符赋值不再被 has_ctor 门槛挡住
- 修复: 外部定义 Counter::inc() 丢失 next_tok 回归
- 新: 派生类 ctor 自动链式调用基类默认 ctor
- 新: tokenizer 跳过 UTF-8 BOM
2026-08-16 18:01:23 +08:00

65 行
1.6 KiB
Markdown

# PCC C++ 阶段 2 实现计划
## 目标
在阶段 1(class/成员函数/构造/继承)基础上,增加:
1. **运算符重载**`operator+``operator==`
2. **命名空间**`namespace` 作用域
3. **引用**`Type&` 引用参数/返回
4. **模板基础**`template <typename T>` 简单模板
5. **虚函数/多态**`virtual` 方法(vtable 简化版)
## 设计
### 1. 运算符重载
```cpp
class Complex {
public:
double re, im;
Complex operator+(const Complex& o) { ... }
};
Complex a, b;
Complex c = a + b; // → Complex_add(&c, &a, &b)
```
- `operator+``Complex_operator_plus``Complex_add`
- `a + b``Complex_add(&tmp, &a, &b)`
### 2. 命名空间
```cpp
namespace math { int add(int a, int b); }
math::add(1,2); // → math_add(1,2)
```
- 名称修饰:`ns::func``ns_func`
- `using namespace` 简化处理
### 3. 引用
```cpp
void swap(int& a, int& b); // → void swap(int *a, int *b)
swap(x, y); // → swap(&x, &y)
```
- 参数 `T& x``T *x`,调用时取地址
### 4. 模板基础
```cpp
template <typename T>
T max2(T a, T b) { return a > b ? a : b; }
max2(3, 5); // 实例化 max2_int
```
- 简单模板:忽略模板头,按调用实例化
### 5. 虚函数(简化)
```cpp
class Shape {
public:
virtual int area() { return 0; }
};
```
- 简化:虚函数当普通成员函数处理(无 vtable)
- 通过基类指针调用子类方法需运行时绑定(暂不支持)
## 实现顺序
1. 运算符重载
2. 命名空间
3. 引用
4. 模板(跳过)
5. 虚函数(降级为普通成员函数)