forked from LearningInfiniTensor/learning-cxx
-
Notifications
You must be signed in to change notification settings - Fork 433
Expand file tree
/
Copy pathmain.cpp
More file actions
58 lines (49 loc) · 1.85 KB
/
main.cpp
File metadata and controls
58 lines (49 loc) · 1.85 KB
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
#include "../exercise.h"
// READ: 复制构造函数 <https://zh.cppreference.com/w/cpp/language/copy_constructor>
// READ: 函数定义(显式弃置)<https://zh.cppreference.com/w/cpp/language/function>
class DynFibonacci {
size_t *cache;
int cached;
public:
// TODO: 实现动态设置容量的构造器
// new size_t[capacity] 申请内存
// {0, 1} 初始化前两个数
// cached(2) 初始化进度
DynFibonacci(int capacity): cache(new size_t[capacity]{0,1}), cached(2) {}
// TODO: 实现复制构造器
// 1. 参数是别人 (other/others)
// 2. 初始化列表:根据别人的进度 (other.cached) 申请一样大的新内存
DynFibonacci(DynFibonacci const &other) : cache(new size_t[other.cached]), cached(other.cached) {
for (int i = 0; i < cached; ++i){
cache[i]=other.cache[i];
}
}
// TODO: 实现析构器,释放缓存空间
~DynFibonacci(){
delete [] cache;
}
// TODO: 实现正确的缓存优化斐波那契计算
size_t get(int i) {
for (; cached<=i; ++cached) {
cache[cached] = cache[cached - 1] + cache[cached - 2];
}
return cache[i];
}
// NOTICE: 不要修改这个方法
// NOTICE: 名字相同参数也相同,但 const 修饰不同的方法是一对重载方法,可以同时存在
// 本质上,方法是隐藏了 this 参数的函数
// const 修饰作用在 this 上,因此它们实际上参数不同
size_t get(int i) const {
if (i <= cached) {
return cache[i];
}
ASSERT(false, "i out of range");
}
};
int main(int argc, char **argv) {
DynFibonacci fib(12);
ASSERT(fib.get(10) == 55, "fibonacci(10) should be 55");
DynFibonacci const fib_ = fib;
ASSERT(fib_.get(10) == fib.get(10), "Object cloned");
return 0;
}