-
Notifications
You must be signed in to change notification settings - Fork 939
Expand file tree
/
Copy pathmain.cpp
More file actions
67 lines (55 loc) · 1.79 KB
/
main.cpp
File metadata and controls
67 lines (55 loc) · 1.79 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
59
60
61
62
63
64
65
66
67
#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: 实现动态设置容量的构造器
DynFibonacci(int capacity): cache(new size_t[capacity]), cached(2) {
cache[0] = 0;
cache[1] = 1;
}
// TODO: 实现复制构造器
DynFibonacci(DynFibonacci const &rhs){
if(&rhs == this) {
return;
}
if(!cache) {
delete[] cache;
}
cache = new size_t[rhs.cached];
cached = rhs.cached;
for(int i = 0;i < cached; ++i) {
cache[i] = rhs.cache[i];
}
};
// TODO: 实现析构器,释放缓存空间
~DynFibonacci(){
delete[] cache;
}
// TODO: 实现正确的缓存优化斐波那契计算
size_t get(int i) {
for (; i >= cached; ++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;
}