http://zhedahht.blog.163.com/blog/static/25411174200722710364233/
上次面试就被问到copy constructor,无奈C++白痴了,这两天狂啃C++ primer和JAVA的时候感觉很多问题似曾相识。
C++果然很强大,用起来神清气爽,是时候入门C++了!
另外看到了stackoverflow上面一个关于unsigned的讨论:
http://stackoverflow.com/questions/2099830/unsigned-keyword-in-c
#include <iostream> using namespace std; template <typename T> class Array { public: Array(unsigned arraysize) : data(0), size(arraysize) { if (size > 0) data = new T[size]; } Array(const Array& copy) : data(0), size(copy.size) { if (size > 0) { data = new T[size]; for (unsigned i = 0; i < size; ++i) setvalue(i, copy.getvalue(i)); } } const Array& operator = (const Array& copy) { if (this == ©) return *this; if (data != NULL) { delete []data; data = NULL; } size = copy.size; if (size > 0) { data = new T[size]; for (unsigned i = 0; i < size; ++i) setvalue(i, copy.getvalue(i)); } } ~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() { Array<int> a(10); Array<int> b(10); b = a; return 0; }