Syntax error: 'constant' and Missing type specifier - int assumed. Note: C++ does not support default-int

Syntax error: 'constant' and Missing type specifier - int assumed. Note: C++ does not support default-int

我正在尝试创建简单的结构。

template <typename T>
struct Element
{
    T eValue;   // Element Value
    Element <T>* next_element;
};


template <typename T, int size>
struct dynamic_array
{
    Element <T> first_element;
    Element <T>* last_element = &first_element;

    add(2);

    void add(int count)
    {
        for (int i = 0; i < count; i++) {
            last_element -> next_element = new Element <T>;
            last_element = last_element -> next_element;
        }
    }
};

如您所见,我尝试在结构中使用 add() 函数,但出现以下错误:

error C2059: syntax error: 'constant'

message : see reference to class template instantiation 'dynamic_array<T,size>' being compiled

error C4430: missing type specifier - int assumed. Note: C++ does not support default-int

warning C4183: 'add': missing return type; assumed to be a member function returning 'int'

但是当我试图从 main() 函数中使用这个函数时,代码编译成功

int main()
{
    dynamic_array <int, 5> myArray;
    myArray.add(5);
}

我不知道为什么会收到这些错误。我可以猜到它是与模板有关的东西,因为我最近开始使用它们

正如 interjay 所指出的,您需要在构造函数中添加代码,以便在创建对象时执行它。但是你应该明白模板与否的基本事实,你正在定义一个结构,编译器会在使用时将它转换成相应的结构(想想一个向量)。现在当你创建模板结构的对象时,内存被分配对于对象,在此之前没有执行任何代码。因此,如果您希望在创建对象后立即执行任何代码,请将代码放在构造函数中,如果您希望代码在特定时间执行,例如此处的 add(int count),则将它们放在成员函数中,然后需要的时候打电话给他们。