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

时间:2012-10-11 02:24:05

标签: c++ abstract-class

我有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中运行时,我收到一个错误“Variable ArrayIntList是一个抽象类” 我不明白这是怎么回事,因为我在上面的.cc文件中定义了它。有什么想法吗?

5 个答案:

答案 0 :(得分:4)

在类ArrayIntList上使用此

virtual void pushBack(int item);

而不是

virtual void pushBack(int item) = 0;

原因是当你为函数声明指定0时,你说它是&#34;纯&#34;,或者没有实现。但是你正在这样做(实现它)。

答案 1 :(得分:3)

您已将ArrayIntList::pushBack(int item)声明为纯虚函数。这就是= 0所做的。从ArrayIntList.h中删除= 0

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

答案 2 :(得分:2)

在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>代替,这样您就不必手动处理内存分配和释放

答案 3 :(得分:0)

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

答案 4 :(得分:0)

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

= 0;

来自ArrayIntList中的等式:

virtual void pushBack(int item) = 0;
相关问题