You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

实现LinkedList类时编译器提示无法声明抽象类型变量问题排查

问题原因与解决方案

核心报错原因

你遇到的抽象类无法实例化问题由两个核心问题导致:

  • 未实现全部基类纯虚函数:基类IList中定义了5个你尚未实现的纯虚函数,只要子类存在未实现的纯虚函数,就会被判定为抽象类,禁止直接实例化。未实现的纯虚函数清单如下:
    virtual bool isEmpty() const = 0;
    virtual bool add(int newEntry) = 0;
    virtual bool remove(int anEntry) = 0;
    virtual void clear() = 0;
    virtual bool contains(int anEntry) = 0;
    
  • 已实现函数签名不匹配:基类中getCurrentSize的签名是带const修饰的virtual int getCurrentSize() const = 0,但你在LinkedList.h中的声明缺少const修饰符,二者属于完全不同的函数,相当于你没有重写基类的纯虚函数,只是新增了一个非const的成员函数。
  • 额外笔误:LinkedList.cpp的display函数中,输出语句错误使用了右移运算符>>,应改为左移运算符<<。

修复步骤

  1. 修正LinkedList.h中getCurrentSize的声明,补全const修饰符,推荐添加override关键字让编译器自动校验重写合法性:
    virtual int getCurrentSize() const override;
    
  2. 在LinkedList.h中补充剩余纯虚函数的声明:
    virtual bool isEmpty() const override;
    virtual bool add(int newEntry) override;
    virtual bool remove(int anEntry) override;
    virtual void clear() override;
    virtual bool contains(int anEntry) override;
    
  3. 在LinkedList.cpp中补充上述5个函数的实现,参考实现示例如下:
    bool LinkedList::isEmpty() const
    {
        return first == nullptr;
    }
    
    bool LinkedList::add(int newEntry)
    {
        // 尾插实现示例
        Node* newNode = new Node{newEntry, nullptr};
        if (first == nullptr) {
            first = newNode;
        } else {
            Node* p = first;
            while (p->next != nullptr) p = p->next;
            p->next = newNode;
        }
        return true;
    }
    
    bool LinkedList::remove(int anEntry)
    {
        Node* p = first, *pre = nullptr;
        while (p != nullptr && p->data != anEntry) {
            pre = p;
            p = p->next;
        }
        if (p == nullptr) return false;
        if (pre == nullptr) first = p->next;
        else pre->next = p->next;
        delete p;
        return true;
    }
    
    void LinkedList::clear()
    {
        Node* p = first;
        while (first) {
            first = first->next;
            delete p;
            p = first;
        }
    }
    
    bool LinkedList::contains(int anEntry)
    {
        Node* p = first;
        while (p != nullptr) {
            if (p->data == anEntry) return true;
            p = p->next;
        }
        return false;
    }
    
  4. 修正display函数的输出运算符错误:
    cout << p->data << " ";
    

完成以上修改后LinkedList就不再是抽象类,可以正常实例化使用。

内容的提问来源于stack exchange,提问作者Hofbr

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.29 04:39:01