C++中的抽象类和纯虚方法
Abstract Class and Pure Virtual Method in C++
我有 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;
- 对纯抽象类中方法的未定义引用
- 用c++中的纯虚拟方法抽象模板类
- 无法实例化抽象类,但类不是抽象/派生方法的参数
- 抽象类/接口中的空方法是否被认为是一种好的做法?
- 如何使用抽象类中未包含的方法
- 确保派生的类实现至少是来自抽象类(C )的两种方法之一
- C :如何在此抽象类的方法中返回抽象类
- 我将如何通过抽象类传递虚拟方法,但可以选择不重写
- 从子类中的抽象类调用方法
- 如何通过方法使用抽象类的子实例?
- 抽象类的需求是什么?为什么要通过其基类访问派生类方法?在C++
- 派生类使用的抽象类的方法
- 使用智能指针将右值引用绑定到抽象类的替代方法
- 在抽象基类中与抽象类成员合作的最佳方法
- 使用纯虚拟方法在C 中初始化抽象类
- C++中的抽象类和纯虚方法
- 我们可以通过在C++中的类中使用关键字“abstract”使所有方法抽象来声明接口类吗
- 带有抽象类的unique_ptr成员和Copy构造函数的Factory方法模式
- C++抽象类参数错误解决方法
- 我们是否有更好的方法来返回C++中的抽象类