CPP基础

文档说明

  • 记录CPP的一些基础用法

基础变量

变量声明

1
2
3
4
int 整型=0;
int[] 数组={2,2,2};
char 字符='a';
String 字符串="我是字符串";

结构体

结构体声明

1
2
3
4
5
6
struct 结构体
{
string 字符串;
int x;
int y;
}

类声明

1
2
3
4
5
6
7
8
9
class Box
{
public:
// 公有成员
protected:
// 受保护成员
private:
// 私有成员
};

函数

回调函数

  • 通过指针函数对函数进行调用
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
#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;
}