【发布时间】:2017-10-18 10:01:12
【问题描述】:
当我尝试只使用 stackType 的构造函数时,编译器说我不能,因为重载的 == 是纯虚拟的。但是,如您所见,我在 stackType 中重新定义了它。请帮忙。 (我认为运算符可以声明为纯虚拟,但我不确定。我是 C++ 新手)。
谢谢!
我将代码缩减到最低限度(学校作业):
#include <iostream>
#include <cstdlib>
#include <cassert>
using namespace std;
template <class Type>
class stackADT
{
public:
virtual bool operator ==(const stackADT<Type> & b) = 0;
};
template <class Type>
class stackType: public stackADT<Type>
{
public:
bool isFullStack() const;
stackType(int stackSize = 100);
bool operator == (const stackType<Type> & b) {
if (this->stackTop != b.stackTop) {
return false;
}
else {
bool equivalence = true;
for (int cntr = 0; cntr < b.stackTop; cntr++) {
if (this->list[cntr] != b.list[cntr]) {
equivalence = false;
}
}
return equivalence;
}
}
private:
int maxStackSize; //variable to store the maximum stack size
int stackTop; //variable to point to the top of the stack
Type *list; //pointer to the array that holds the
//stack elements
};
template <class Type>
bool stackType<Type>::isFullStack() const
{
return(stackTop == maxStackSize);
} //end isFullStack
template <class Type>
template <class Type>
stackType<Type>::stackType(int stackSize)
{
if (stackSize <= 0)
{
cout << "Size of the array to hold the stack must "
<< "be positive." << endl;
cout << "Creating an array of size 100." << endl;
maxStackSize = 100;
}
else
maxStackSize = stackSize; //set the stack size to
//the value specified by
//the parameter stackSize
stackTop = 0; //set stackTop to 0
list = new Type[maxStackSize]; //create the array to
//hold the stack elements
}//end constructor
int main() {
stackType<int> a(34);
}
【问题讨论】:
-
请edit您的问题提供minimal reproducible example。
-
不要在基类中实现
operator=。您允许子类与不同类型的子类进行比较。例如,给定一个Shape基类,您可以将正方形与圆形进行比较。
标签: c++ operator-overloading pure-virtual