因此,我一直在尝试使用 Nodes,并在尝试测试时不断遇到此错误。如果我使用括号,我会在 list.
上收到此错误 - “Expression must have class type!”
如果我不使用括号,我会在 list
、insert
和 display
上收到此错误 - “这是不可访问的。”
在 Main() 中声明我的 LList 时会发生这种情况。这是怎么回事,为什么会这样?
我的司机
#include "LList.h"
#include <iostream>
using namespace std;
int main()
{
LList<int> list;
bool test = list.insert(5);
list.display();
return 0;
}
LList 类
#include "Nodes.h"
#ifndef LLIST_H
#define LLIST_H
template<typename TYPE>
class LList
{
Node<TYPE>* front;
LList();
~LList();
bool insert(const TYPE& dataIn);
void display() const;
};
template<typename TYPE>
LList<TYPE>::LList()
{
front = null;
};
template<typename TYPE>
LList<TYPE>::~LList()
{
Node<TYPE>* temp;
while(front)
{
temp = front;
front = fornt -> next;
delete temp;
}
};
template<typename TYPE>
bool LList<TYPE>::insert(const TYPE& dataIn)
{
bool success = false;
Node<TYPE> pBefore = null;
Node<TYPE> pAfter = front;
while(pAfter && PAfter->data < dataIn)
{
pBefore = pAfter;
pAfter = pAfter->next;
}
if(Node<TYPE>* store = new Node<TYPE>)
store->data = dataIn
return success;
};
template<typename TYPE>
void LList<TYPE>::display() const
{
TYPE* temp = front;
while(front && temp->next != null)
{
cout << temp->data << endl;
}
};
#endif
类节点
#ifndef NODES_H
#define NODES_H
template<typename TYPE>
struct Node
{
Node<TYPE>* next;
TYPE data;
Node();
Node(TYPE d, Node<TYPE> n);
};
template<typename TYPE>
Node<TYPE>::Node()
{
data = 0;
next = null;
};
template<typename TYPE>
Node<TYPE>::Node(TYPE d, Node<TYPE> n)
{
data = d;
next = n;
};
#endif
最佳答案
你的错误是你的类声明的结果:
template<typename TYPE>
class LList
{
Node<TYPE>* front;
LList();
~LList();
bool insert(const TYPE& dataIn);
void display() const;
};
线索在“这是无法访问的”错误中。因为您没有提供任何访问修饰符,所以该类的所有成员都默认为私有(private)。要解决此问题,您只需标记类(class)的公共(public)和私有(private)部分:
template<typename TYPE>
class LList
{
public:
LList();
~LList();
bool insert(const TYPE& dataIn);
void display() const;
private:
Node<TYPE>* front;
};
通过此更改,您的代码在 list
的变量声明末尾应该可以带或不带括号。
关于c++ - 表达式必须有类类型?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12557655/