我有一个相当简单的问题,我通常可以调试自己,但我现在似乎遇到了很多问题。
我正在创建一个链表数据结构,我创建了两个函数,一个用于返回前面的Elem,另一个用于返回最后一个Elem。问题是编译器说Elem没有定义类型。
以下是修剪相关代码的头文件:
class simpleList {
public:
//Returns a pointer to the first Elem of the list
simpleList::Elem* front();
//Returns a pointer to the last Elem of the list
simpleList::Elem* back();
private:
struct Elem {
char info;
Elem *next;
};
Elem *head;
};
以下是这两个函数的.cpp文件实现:
//Returns a pointer to the first Elem of the list
simpleList::Elem* simpleList::front()
{
return head;
}
//Returns a pointer to the last Elem of the list
simpleList::Elem* simpleList::back()
{
Elem * temp = head;
while( temp -> next != 0 )
temp = temp -> next;
return temp;
}
我已经尝试过将它们放到课堂上,只是这样做:
Elem* simpleList::front()
Elem* simpleList::back()
错误消息如下: simpleList.h:38:9:错误:'class simpleList'中的'Elem'没有命名类型 simpleList.h:41:9:错误:'class simpleList'中的'Elem'没有命名类型
答案 0 :(得分:1)
请尝试此订单以进行类声明:
class simpleList {
public:
struct Elem {
char info;
Elem *next;
};
//Returns a pointer to the first Elem of the list
Elem* front();
//Returns a pointer to the last Elem of the list
Elem* back();
private:
Elem *head;
};
答案 1 :(得分:0)
对于您输入的代码,我会收到更多错误:http://ideone.com/c9PHc
以下是有关错误的详细信息,以及为何Bo的回答有效。
排序错误,因此您在定义之前使用了类型Elem
。您必须至少告诉编译器它存在并且它是您的类的嵌套类型。否则它将达到这一点,不知道如何处理它。
您的struct Elem
是私密的。即这种类型只能在同一个类的私有部分中看到,就像私有变量一样。您从公共方法返回此结构,因此返回值是公共部分,此结构无法看到。仅更改排序但不同时公开类型意味着您可以调用simpleList::front()
和simpleList::back()
,但不能将返回类型存储在任何位置(因为这需要具有私有类型的变量)
您的返回值声明中有重复的范围说明符。这不是错误,但它们并不是真正必要的,可能会使其他人感到困惑。通常在类级别,您只需直接使用嵌套类型而无需额外的作用域指示符。
因此,在这种情况下,不仅仅是重要的顺序,而是错误的实际组合。计数1导致您看到的编译器错误,计数2将导致您的方法无法使用,并可能导致其他地方的编译器错误,而计数3仅仅是美学。