gpt4 book ai didi

c++ - 创建自己的vector Class,错误很多

转载 作者:行者123 更新时间:2023-11-28 03:07:41 24 4
gpt4 key购买 nike

我是 C++ 的新手,使用它创建类,尤其是使用模板类。我收到了很多错误消息,但我不确定如何解决它们,希望这里有人能提供帮助,在此先感谢。

类:

template <class T> class Vector {
public:
typedef T* iterator;
Vector();
iterator begin();
iterator end();
int size();
iterator insert(iterator position, const T& item);
void alloc_new();

private:
T items;
int used;
};

template <class T> Vector::Vector() {
items = [1000];
used = 0;
}

template <class T> iterator Vector::begin() {
return items;
}

template <class T> iterator Vector::end(){
return items + used;
}

template <class T> int Vector::size() {
return used;
}

template <class T> iterator Vector::insert(iterator position, const T& item){

if (used+1 > items){
alloc_new();}

items[position] = item;
used =+ 1;

}

template <class T> void Vector::alloc_new(){
items = used*2;
T tmp[] = items;

for (int i = 0; i < used; i++){
tmp[i] = items[i];
}
delete items;
items = tmp;
}

错误信息:

main.cpp:67: error: `template class Vector' used without template parametersmain.cpp:67: error: ISO C++ forbids declaration of `Vector' with no typemain.cpp:67: error: declaration of template `template int Vector()'main.cpp:52: error: conflicts with previous declaration `template class Vector'main.cpp:52: error: previous non-function declaration `template class Vector'main.cpp:67: error: conflicts with function declaration `template int Vector()'main.cpp: In function `int Vector()':main.cpp:68: error: `items' undeclared (first use this function)main.cpp:68: error: (Each undeclared identifier is reported only once for each function it appears in.)main.cpp:68: error: expected primary-expression before '[' tokenmain.cpp:69: error: `used' undeclared (first use this function)main.cpp: At global scope:main.cpp:72: error: expected constructor, destructor, or type conversion before "Vector"main.cpp:72: error: expected `;' before "Vector"main.cpp:76: error: expected constructor, destructor, or type conversion before "Vector"main.cpp:76: error: expected `;' before "Vector"main.cpp:80: error: `template class Vector' used without template parametersmain.cpp: In function `int size()':main.cpp:81: error: `used' undeclared (first use this function)main.cpp: At global scope:main.cpp:84: error: expected constructor, destructor, or type conversion before "Vector"main.cpp:84: error: expected `;' before "Vector"main.cpp:94: error: `template class Vector' used without template parametersmain.cpp: In function `void alloc_new()':main.cpp:95: error: `items' undeclared (first use this function)main.cpp:95: error: `used' undeclared (first use this function)

最佳答案

您需要指定模板参数。例如:

template <class T> Vector<T>::Vector() { 
items = [1000]; // note, this is also invalid syntax
used = 0;
}

关于c++ - 创建自己的vector Class,错误很多,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19308612/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com