当我尝试使用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);
}
答案 0 :(得分:3)
operator==
中的{p> stackADT
采用const stackADT<Type>&
类型的参数,operator==
中的stackType
采用const stackType<Type>&
类型之一。由于它们具有不同的签名,因此它们具有不同的功能。
如果要确保派生类中的函数覆盖基类中的函数,则可以(在C ++ 11中)使用override
关键字。如果你的函数没有覆盖任何东西,它会让编译器抱怨。
就目前而言,你的抽象基础要求每个派生类都与基数相当。因此,您只能将比较基于基础中可用的成员。由于比较应该是可传递的,这也意味着可以仅基于基类中存在的成员来比较不同的派生类。如果这不是你想要的,你应该从基地移除操作员。
答案 1 :(得分:1)
此
bool operator == (const stackType<Type> & b)
不会覆盖
virtual bool operator ==(const stackADT<Type> & b) = 0
因为参数类型不同。第一个引用stackType<Type>
的const引用。第二个对stackADT<Type>.
进行const引用所以在派生类中有两个不同的operator ==函数,第一个是纯虚函数 - 因此编译错误。
这里引用了几种解决方法: Dynamic Casts or Function Overloads?一种方法涉及使用dynamic_cast,另一种方法使用双重调度。