实现一个简单的Vector时遇见了一些问题
我不是编程新手,但也算是C++新手了,今天尝试着写一个简单的Vector,一心想能够实现简单的迭代功能就够了。可是C++的语法似乎是一道坎啊!
程序代码:
#include <vector> #include <iostream> #include <algorithm> using namespace std; template<typename Type> struct print { void operator()(Type& i) { cout << i << endl; } }; template<typename T> class MyVector { public: typedef T* iterator; MyVector(int& size):_size(size):_first(NULL) { alloc(); } ~MyVector() { if(NULL == _first) return; delete _first; _first = NULL; } void alloc() throw(std::bad_alloc) { try{ _first = operator new(_size * sizeof(T)); }catch(...){ throw; } } iterator begin() { return _first; } iterator end() { return _first + _size; } private: // MyVector(); // MyVector(MyVector&); int _size; iterator _first; }; int main() { int myints[] = {1, 2, 3, 4, 5, 6, 7}; MyVector<int>myvector(7); std::copy(myints, myints + 7, myvector.begin()); for_each(myvector.begin(), myvector.end(), print<int>()); return 0; }
编译出错,编译器的错误提示为:
程序代码:
copy.cpp: 在构造函数‘MyVector<T>::MyVector(int&)’中: copy.cpp:20:36: 错误: expected ‘{’ before ‘:’ token copy.cpp: 在函数‘int main()’中: copy.cpp:57:28: 错误: 对‘MyVector<int>::MyVector(int)’的调用没有匹配的函数 copy.cpp:57:28: 附注: 备选是: copy.cpp:20:5: 附注: MyVector<T>::MyVector(int&) [with T = int] copy.cpp:20:5: 附注: no known conversion for argument 1 from ‘int’ to ‘int&’ copy.cpp:16:7: 附注: MyVector<int>::MyVector(const MyVector<int>&) copy.cpp:16:7: 附注: no known conversion for argument 1 from ‘int’ to ‘const MyVector<int>&’