Skip to the content.

杂记

如何调用 posix 中内容

cpp 并没有完整的封装,也就是 fstream 不能完全替代所有的内容:

可以参考: https://android.googlesource.com/platform/system/libbase/+/refs/heads/main/file.cpp

  ReadFileToString(path, content)
    │
    ├─ open() 打开文件
    ├─ unique_fd 接管文件描述符
    └─ ReadFdToString()
         └─ 循环 read()
              ├─ 被信号中断:重试
              ├─ 读到数据:追加到 std::string
              ├─ 到达 EOF:返回 true
              └─ 读取失败:返回 false,保留 errno

C++ 成员函数指针

什么时候使用

它适合需要保存一个对象方法、稍后再调用的场景。

回调

class Button {
public:
    void on_click(int x) {
        // 处理点击
    }
};

using Handler = void (Button::*)(int);

void call_handler(Button& button, Handler handler) {
    (button.*handler)(123);
}

在几个成员函数之间选择一个

class Calculator {
public:
    int add(int a, int b) { return a + b; }
    int sub(int a, int b) { return a - b; }
};

Calculator calculator;
int (Calculator::*operation)(int, int) = &Calculator::add;

int result = (calculator.*operation)(1, 2);

事件系统、GUI、定时器和一些旧式 C++ 框架也可能要求传入成员函数指针作为回调。

一般不建议使用这个,只是说,c++ 支持这个能力而已罢了。

enum class

https://github.com/Neargye/magic_enum

需要找找 xiaopeng teacher 的课程看看

union

本站所有文章转发 CSDN 将按侵权追究法律责任,其它情况随意。