use*_*215 17 c++ templates typename
我有一个好奇的问题,我不太清楚问题是什么.我正在创建一个名为LinkedArrayList的类,它使用typename模板,如下面的代码所示:
#pragma once
template <typename ItemType>
class LinkedArrayList
{
private:
class Node {
ItemType* items;
Node* next;
Node* prev;
int capacity;
int size;
};
Node* head;
Node* tail;
int size;
public:
void insert (int index, const ItemType& item);
ItemType remove (int index);
int find (const ItemType& item);
};
Run Code Online (Sandbox Code Playgroud)
现在,这不会给出任何错误或问题.但是,在.cpp文件中创建函数会给出错误"类模板的参数列表'LinkedArrayList'缺失." 它还说ItemType未定义.这是代码,非常简单,在.cpp中:
#include "LinkedArrayList.h"
void LinkedArrayList::insert (int index, const ItemType& item)
{}
ItemType LinkedArrayList::remove (int index)
{return ItemType();}
int find (const ItemType& item)
{return -1;}
Run Code Online (Sandbox Code Playgroud)
看起来它与模板有关,因为如果我将它注释掉并将函数中的ItemTypes更改为int,它不会给出任何错误.另外,如果我只是在.h中执行所有代码而不是单独的.cpp,它也可以正常工作.
任何有关问题根源的帮助将不胜感激.
谢谢.
And*_*owl 18
首先,这是您应该如何为类模板的成员函数提供定义:
#include "LinkedArrayList.h"
template<typename ItemType>
void LinkedArrayList<ItemType>::insert (int index, const ItemType& item)
{}
template<typename ItemType>
ItemType LinkedArrayList<ItemType>::remove (int index)
{return ItemType();}
template<typename ItemType>
int LinkedArrayList<ItemType>::find (const ItemType& item)
{return -1;}
Run Code Online (Sandbox Code Playgroud)
其次,这些定义不能放在.cpp
文件中,因为编译器无法从它们的调用点隐式地实例化它们.例如,请参阅StackOverflow上的此问答.
归档时间: |
|
查看次数: |
51652 次 |
最近记录: |