c++ - 表达式必须有类类型?

标签 c++ class object linked-list nodes

因此,我一直在尝试使用 Nodes,并在尝试测试时不断遇到此错误。如果我使用括号,我会在 list. 上收到此错误 - “Expression must have class type!”

如果我不使用括号,我会在 listinsertdisplay 上收到此错误 - “这是不可访问的。”

在 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/

相关文章:

c++ - QML 动画结束后调用 C++ 函数

python - 管理(和重命名)类组合的实例变量

java - 获取通用类

javascript - 合并来自具有相同键的不同对象的数组

scala - Scala中嵌套对象的类型是什么

c++ - Boost Log 多个文件轮换

c++ - WCOUT 和 COUT 中未打印的 ASCII 字符

arrays - 如何使用 jq 将字符串数组转换为对象?

c++ - 指向另一个类的方法的指针

python : Reverse Order Of List