基础代码面

实现可变长数组

这种问题要记住实现两版,一定不要忘了写const对象的版本

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
#include <iostream>
using namespace std;

class Array{
public:
Array(int length = 0);
~Array();
public:
int & operator[](int i);
const int & operator[](int i) const;
public:
int length() const { return m_length; }
void display() const;
private:
int m_length; //数组长度
int *m_p; //指向数组内存的指针
};

Array::Array(int length): m_length(length){
if(length == 0){
m_p = NULL;
}else{
m_p = new int[length];
}
}

Array::~Array(){
delete[] m_p;
}

int& Array::operator[](int i){
return m_p[i];
}

const int & Array::operator[](int i) const{
return m_p[i];
}

void Array::display() const{
for(int i = 0; i < m_length; i++){
if(i == m_length - 1){
cout<<m_p[i]<<endl;
}else{
cout<<m_p[i]<<", ";
}
}
}

int main(){
int n;
cin>>n;

Array A(n);
for(int i = 0, len = A.length(); i < len; i++){
A[i] = i * 5;
}
A.display();

const Array B(n);
cout<<B[n-1]<<endl; //访问最后一个元素

return 0;
}


这周日争取学一下github新出的markdown神器,顺便这两篇文章中的代码高亮方法:语雀链接(仅我可见)