c++ - 模板声明不能出现在块范围内
问题描述
所以这是给我的课的,坦率地说,我以前从未使用过模板。这是我的简单 vector.h 文件,但我一直收到模板不能出现在块范围内的错误。我对此的理解是,这表明我正在尝试在函数中定义它。这是我的代码:
#ifndef SIMPLEVECTOR_H
#define SIMPLEVECTOR_H
#include <iostream>
#include <new> // Needed for bad-alloc exception
#include <cstdlib> // Needed for the exit function
using namespace std;
template <class T>
class SimpleVector {
private:
T *aptr; // To point to the allocated array
int arraysize; // Number of elements in the array
void memError(); // Handles memory allocation errors
void subError(); // Handles subscripts out of range
public:
SimpleVector()
{
aptr = 0; arraysize = 0;
}
SimpleVector(int s);
SimpleVector(const SimpleVector &);
~SimpleVector();
int size() const
{
return arraysize;
}
T getElementAt(int sub);
T &operator[](const int &);
};
#endif //SIMPLEVECTOR_H
template <class T>
SimpleVector<T>::SimpleVector(int s)
{
if(s<1)
{
arraysize=1;
}
else
{
arraysize=s;
}
try
{
aptr = new T [arraysize];
}
catch (bad_alloc)
{
memError();
}
for(int i=0;i<arraysize;i++)
{
aptr[i]=0;
{
}
template <class T>
void SimpleVector<T>::memError()
{
cout<<"Error: cannot allocate memory."<<endl;
exit(EXIT_FAILURE);
}
template <class T>
T SimpleVector<T>::getElementAt(int sub)
{
return aptr[sub];
}
template <class T>
SimpleVector<T>::~SimpleVector()
{
if(arraysize>0)
{
aptr.clear();
aptr=aptr[0];
}
}
template <class T>
void SimpleVector<T>::subError()
{
cout<<"Subscripts out of range."<<endl;
exit(EXIT_FAILURE);
}
然后这是我遇到的错误。
In file included from main.cpp:4:0:
simplevector.h: In constructor ‘SimpleVector<T>::SimpleVector(int)’:
simplevector.h:87:1: error: a template declaration cannot appear at block scope
template <class T>
^
simplevector.h:99:1: error: expected ‘;’ before ‘template’
template <class T>
^
simplevector.h:109:1: error: a template declaration cannot appear at block scope
template <class T>
^
simplevector.h:122:1: error: expected ‘;’ before ‘template’
template <class T>
^
main.cpp:9:1: error: a function-definition is not allowed here before ‘{’ token
{
^
main.cpp:47:1: error: expected ‘}’ at end of input
}
^
main.cpp:47:1: error: expected ‘}’ at end of input
make: *** [main.o] Error 1
任何见解或帮助都会很棒!
解决方案
在你的
template <class T>
SimpleVector<T>::SimpleVector(int s)
for
最后循环的左大括号和右大括号不匹配。
在析构函数中,您应该将向量清除为aptr->clear();
,因为aptr
它是一个指针变量。
推荐阅读
- tensorflow - tf.debugging.enable_check_numerics() 的内存使用情况
- c# - Csharp中双重声明后的字母是什么?
- dictionary - 覆盖字典中的一个变量
- c# - 如何在 MVC 上显示包含来自 csv 文件的添加项目的静态列表
- java - 如何调用驻留在 Maven 本地存储库中的 JAR?
- python - IntegrityError: UNIQUE 约束失败,如何捕获和响应
- python - 如何在菜单颜色kivy中填充屏幕切口?
- django - 比萨订购网站django
- php - 正则表达式在字符串中查找出现并返回从字符开头到字符结尾的匹配块
- javascript - 使用 Javascript 函数跨越单击按钮的特定类中的类