cpp学习CPP基础凝雨2025-03-152025-03-15文档说明 记录CPP的一些基础用法 基础变量变量声明1234int 整型=0;int[] 数组={2,2,2};char 字符='a';String 字符串="我是字符串"; 结构体结构体声明123456struct 结构体{string 字符串;int x;int y;} 类类声明123456789class Box{ public: // 公有成员 protected: // 受保护成员 private: // 私有成员}; 函数回调函数 通过指针函数对函数进行调用 12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091#include <cassert>#include <iostream>#include <functional>using namespace std;class MyClass {public: // 构造函数 MyClass(int initialValue=10) : value(initialValue) { initCallback(); } // 设置属性值并触发回调 void setValue(int newValue) { if (newValue==value) return; value = newValue; if(callback) { callback(value); } } void set_price(int newValue) { if (newValue==price) return; price = newValue; //调用回调函数 if(callback) { callback(price); } } //初始化回调函数 void initCallback() { //callback = [this](int newValue) { myCallback(newValue); }; callback = [this](int newValue) { try { myCallback(newValue); } catch (const std::exception& e) { std::cerr << "Callback exception: " << e.what() << std::endl; } }; assert(callback != nullptr); // 确保回调函数不为空 } virtual void myCallback(int newValue) { cout << "Value changed toa: " << newValue << endl; }private: int value; // 属性 int price; function<void(int)> callback; // 回调函数};class MyClassA:public MyClass{public: MyClassA(){}; void myCallback(int newValue) override { cout << u8"重写: " << newValue << endl; }};int main() { MyClass obj(10); MyClassA objA; objA.set_price(60); // 更改属性值 obj.setValue(100); // 输出: Value changed to: 10 obj.setValue(20); // 输出: Value changed to: 20 obj.set_price(30); return 0;}