哪位老大能帮我编译一下

adventurelw adventurelw 墨衍会员 · AI 创作全网分发 墨衍智能分发 通过墨衍一键同步至各平台 可同步平台 CSDN微信公众号微博知乎掘金百家号博客园抖音小红书 你的文章也可以这样分发 墨衍会员 ¥399起/年,写一次发全网 我也要 + 加入社区
代码

#include <algorithm>
#include <memory>

template <typename T>
class Vector
{
public:
typedef T * iterator;
typedef std::size_t size_type;
private:
static std::allocator<T> alloc;//一个静态对象所有Vector<T>对象可以公用,调用相应的成员函数分配不同的空间
iterator element;
iterator first_free;
iterator end;
void destory();//销毁元素及释放内存
template <typename iter>
void copy_elem(iter b, iter e);//复制元素
void reallocate();//重新分配足够空间,一般是原来空间的两倍
public:
Vector() : element(0), first_free(0), end(0) {}
template <typename iter>
Vector(iter b, iter e);//使用同类模版构造
Vector(size_type n, const T &t);
Vector(const Vector &vec);//复制构造
~Vector() { destory(); }
Vector &operator =(const Vector &vec);//赋值重载
void push_back(const T &t);
size_type size() const { return first_free - element; }
void resize(size_type new_size, const T &t);
void reserved(size_type n);//重新分配空间
size_type capacity() const { return end - element; }
T &operator [](size_type i) { return *(element + i); }
const T &operator [](size_type i) const { return *(element + i); }
};

template <typename T>
void Vector<T>::resize(Vector<T>::size_type new_size, const T &t)
{
if(size() < new_size)
{
if(capacity() < new_size)
reallocate();
uninitialized_fill(first_free, element + new_size, t);
}
else
{
T *p = first_free;
while(p != element + new_size)
alloc.destroy(--p);
}
first_free = element + new_size;
}//重新调正容器大小


Primer的一个习题,实现vector类模版
问题,resize成员在如上定义和实现的情况下编译不能通过
错误看不太懂,如下:
警告 1 warning C4346: “Vector<T>::size_type”: 依赖名称不是类型 d:\my document\visual studio 2005\projects\test1\test1\textquery.h 39
错误 2 error C2146: 语法错误 : 缺少“)”(在标识符“new_size”的前面) d:\my document\visual studio 2005\projects\test1\test1\textquery.h 39
错误 3 error C2182: “resize”: 非法使用“void”类型 d:\my document\visual studio 2005\projects\test1\test1\textquery.h 39
错误 4 error C2470: “Vector<T>::resize”: 看起来像函数定义,但没有参数列表;跳过明显的函数体 d:\my document\visual studio 2005\projects\test1\test1\textquery.h 39
错误 5 error C2072: “Vector<T>::resize”: 函数的初始化 d:\my document\visual studio 2005\projects\test1\test1\textquery.h 39
错误 6 error C2059: 语法错误 : “)” d:\my document\visual studio 2005\projects\test1\test1\textquery.h 39

以上是vs2005的结果,在2008下更怪,还会连带把一个源文件(以上是在头文件中实现的)中的

int main()
{
return 0;
}

编译出两个错误来,都是语法错误,花括号之类的

而上面的代码语法上应该没有什么大的问题(或许有,那就是我没看见的),因为如果将resize的实现在类定义中实现,也就是直接copy到类定义的花括号中(按照内联函数定义),当然,去掉重复多余的部分,编译则可以正确。我查STL实现也是作为内联函数来实现的,但并不明白为何在类外实现则不可行?目前为止,只有这一个不可以,其余(capacity()还没来得及实现)的都没有问题,可以编译通过。
希望能够获得一些经验,谢谢大家。
...全文

相关推荐

评论 7
收藏 已收藏
分享
返回顶部
adventurelw
C++ 语言 65,212 成员 250,513 内容