![]() |
#2
thlgood2013-05-17 15:04
|
可是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>&’