注册 登录
编程论坛 C++教室

C++模板类 紧急

蓝色的blue 发布于 2015-05-15 11:57, 517 次点击
#ifndef LLIST_H
#define LLIST_H
struct Sub;
typedef Sub* POSITION;
#include <iostream>
using namespace std;

template<class T>
class List
{
public:
    struct Sub
    {
        T a;
        Sub*next;
    };
public:
    List();
    bool add(T temp);
    POSITION getHeadPosition();
    T getNext(POSITION rpos);
    unsigned int getSize();
    T display()
    {
        return (head->a);
    }
private:
    Sub* head;
    unsigned int count;
};
template<class T>
List<T>::List()
{
    head=NULL;
    count=0;
}
template<class T>
bool List<T>::add(T temp)
{
    if(head==NULL)//创建头结点
    {
        head=new Sub;
        head->a=temp;
        head->next=NULL;
        count++;
        return true;
    }
    Sub* pHead=head;
    while(pHead)
    {
        pHead=pHead->next;
    }
    pHead=new Sub;
    pHead->a=temp;
    pHead->next=NULL;
    count++;
    return true;
}
template<class T>
POSITION List<T>::getHeadPosition()
{
    return head;
}
template<class T>
T List<T>::getNext(POSITION rpos)
{
    if(rpos==NULL)
        return NULL;
    POSITION temp=rpos;
    rpos=(POSITION)rpos->next;
    return temp->a;
}
template<class T>
unsigned int List<T>::getSize()
{
    return count;
}
#endif
请问大神为什么我的getNext()函数中最后两行语句为什么会出错?
出错信息如下:
list.h(70): error C2227: “->next”的左边必须指向类/结构/联合/泛型类型
1>e:\vscode\moban\moban\list.h(71): error C2027: 使用了未定义类型“Sub”
1>          e:\vscode\moban\moban\list.h(3) : 参见“Sub”的声明
1>e:\vscode\moban\moban\list.h(71): error C2227: “->a”的左边必须指向类/结构/联合/泛型类型
1 回复
#2
rjsp2015-05-15 14:58
你这代码……,我就不看了,以下修改只求能让它编译通过。

1. 删掉
struct Sub;
typedef Sub* POSITION;

2. 在
struct Sub
{
    T a;
    Sub*next;
};
后增加一句 typedef Sub* POSITION;

3. 修改
POSITION List<T>::getHeadPosition()

typename List<T>::POSITION List<T>::getHeadPosition()
1