我遇到了一些错误,[E1]“C ++需要所有声明的类型说明符”,[E2]“使用未声明的标识符”和[E3]“预期的类名或命名空间”。
#ifndef MAIN_SAVITCH_SEQUENCE_H
#define MAIN_SAVITCH_SEQUENCE_H
template <class T>
class sequence
{
public:
// TYPEDEFS and MEMBER CONSTANTS
typedef T value_type;
static const int CAPACITY = 30;
// CONSTRUCTOR
sequence( );
// MEMBER FUNCTIONS
void showSequence();
void attach(value_type entry);
value_type current( );
void remove_current( );
int size( );
private:
value_type data[CAPACITY];
int used;
};
template <class T>
[E3] sequence::sequence( )
{
[E2] used = 0;
}
template <class value_type>
[E3] void sequence::attach(value_type entry)
{
data[used++] = entry;
}
sequence::value_type sequence::current( )
//replace sequence::value_type with typename value_type for your template
{
return data[used-1];
}
void sequence::remove_current( )
{
used--;
}
int sequence::size( )
{
return used;
}
void sequence::showSequence()
{
std::string display = "";
for (int i = 0; i<used; i++)
std::cout << data[i] << "\n";
}
#endif
答案 0 :(得分:5)
您可以简单地在模板类中定义函数
template <class T>
class sequence
{
//...
sequence() : used(0) // define function inside template class.
{
}
//...
}
或者您需要在模板声明之外定义的每个函数之前添加template <class T>
和<T>
:
template <class T>
sequence<T>::sequence( )
^^^^^^^^^^^
{
used = 0;
}
template <class value_type>
void sequence<T>::attach(value_type entry)
^^^^^^^^^^^
{
data[used++] = entry;
}
template <class T>
typename sequence<T>::value_type sequence<T>::current( )
^^^^^^^^ // 1. value_type comes from sequence template, so you need to specify sequence<T>
^^^^^^^
// 2. sequence<T>::value_type type depends on template parameter, so typename is needed
{
return data[used-1];
}
如何使用它:
sequence<int> test;
^^^^ // sequence is a template, you need to specify a type