C++中的抽象类和纯虚方法

Abstract Class and Pure Virtual Method in C++

本文关键字:方法 抽象类 C++      更新时间:2023-10-16

我有 4 个C++文件、2 个标头和 2 个 .cc 文件。这只是一个概念证明,但我似乎无法正确理解。

我的第一个标题如下所示:

#ifndef INT_LIST_H
#define INT_LIST_H
class IntList
{
  public:
     //Adds item to the end of the list
     virtual void pushBack(int item) = 0;
};
#endif

我的第二个标题使用第一个标题,如下所示:

#ifndef ArrayIntList_H
#define ArrayIntList_H
#include "IntList.h"

class ArrayIntList : public IntList
{
    private:
        int* arrayList;
        int* arrayLength;
     public:
        //Initializes the list with the given capacity and length 0
        ArrayIntList(int capacity);
        //Adds item to the end of the list
        virtual void pushBack(int item) = 0;
};
#endif  

我的第一个 .cc 文件填充了前一个类的方法:

#include <iostream>
#include "ArrayIntList.h"
ArrayIntList::ArrayIntList(int capacity)
{
    //make an array on the heap with size capacity
    arrayList = new int[capacity];
    //and length 0
    arrayLength = 0; 
}
void ArrayIntList::pushBack(int item)
{
    arrayList[*arrayLength] = item;
}

这是我的主要功能:

#include <iostream>
#include "ArrayIntList.h"
int main(int argc, const char * argv[])
{
    ArrayIntList s(5);
}

当我在 Xcode 中运行它时,我收到一个错误,指出"变量 ArrayIntList 是一个抽象类"我不明白这是怎么回事,因为我在上面的 .cc 文件中定义了它。有什么想法吗?

在类 ArrayIntList 上使用此

virtual void pushBack(int item);

而不是这个

virtual void pushBack(int item) = 0;

原因是当你给函数声明赋值 0 时,你说它是"纯的",或者没有实现。但是你在下面这样做(实现它)。

你已经ArrayIntList::pushBack(int item)声明为一个纯虚函数。 这就是= 0的作用。 从 ArrayIntList.h 中删除= 0

另外:您使用 int 指针而不是 int 来跟踪数组长度。

在 ArrayIntList 类的声明中,需要从方法声明中删除"= 0"。您可能还需要将 arrayLength 声明为 int,而不是指向 int 的指针。最后,由于您要为构造函数中的数组分配内存,因此您应该声明一个析构函数,以便在销毁对象时释放内存:

class ArrayIntList : public IntList
{
private:
    int* arrayList;
    int arrayLength;
public:
    //Initializes the list with the given capacity and length 0
    ArrayIntList(int capacity);
    virtual ~ArrayIntList() { delete arrayList; }
    //Adds item to the end of the list
    virtual void pushBack(int item);
};

当然,处理数组列表的最佳方法是改用std::vector<int>,这样您就不必手动处理内存分配和释放

在类 ArrayIntList 中,您声明了一个纯虚拟的"虚拟 void pushBack(int item) = 0;",您已经在抽象父 IntList 中声明了该声明。 您需要做的就是将其声明为"虚拟 void pushBack(int item);"。

一个抽象基类不能从另一个抽象基类继承,删除

= 0;

从 ArrayIntList 中的公式:

virtual void pushBack(int item) = 0;