题目:下面是一个数组类的声明与实现。请分析这个类有什么问题,并针对存在的问题提出几种解决方案。
#include "iostream"
#include <algorithm>
#include <functional>
using namespace std;
template<typename T> class Array {
public:
Array(unsigned arraySize):data(0), size(arraySize) {
if(size > 0)
data = new T[size];
}
~Array() {
if(data)
delete[] data;
}
void setValue(unsigned index, const T& value) {
if(index < size)
data[index] = value;
}
T getValue(unsigned index) const {
if(index < size)
return data[index];
else
return T();
}
private:
T* data;
unsigned size;
};
int main(void){
Array<int>a(3);
Array<int>b(4);
b=a;
a.setValue(0,0);
a.setValue(1,1);
a.setValue(2,2);
b.~Array();
cout<<a.getValue(2);
return 0;
}
我们在大学的学习中对于这些类的性质和写法的注意点基本上是忽视的,这道题正好可以弥补这一点,受教了,详细讲解见程序员面试提精讲100题,得好好看
看http://zhedahht.blog.163.com/blog/static/25411174200722710364233/