编译器说定义的函数是虚拟的
Compiler says that defined function is virtual
当我尝试只使用 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);
}
stackADT
中的operator==
采用类型 const stackADT<Type>&
的参数,operator==
stackType
中的参数采用类型 const stackType<Type>&
的参数之一。由于它们具有不同的签名,因此它们是不同的功能。
如果要确保派生类中的函数覆盖基类中的函数,则可以(在 C++11 中)使用 override
关键字。如果您的函数不覆盖任何内容,它将使编译器抱怨。
就目前而言,您的抽象基要求每个派生类都与基类相当。因此,您只能基于基库中可用的成员进行比较。由于比较应该是可传递的,这也意味着可以仅基于基类中存在的成员来比较不同的派生类。如果这不是您想要的,则应从基座中删除运算符。
bool operator == (const stackType<Type> & b)
不覆盖
virtual bool operator ==(const stackADT<Type> & b) = 0
因为参数类型不同。 第一个采用对stackType<Type>
的常量引用。 第二个采用对stackADT<Type>.
的常量引用 因此,派生类中有两个不同的 operator== 函数,第一个是纯虚拟函数 - 因此编译器错误。
此处参考了解决此问题的几种方法:动态强制转换还是函数重载?一种方法涉及使用dynamic_cast,另一种方法使用双重调度。
相关文章:
- C++无法定义虚拟函数 OUTER 类和头文件
- 用常见虚拟函数实现的任意组合来实现派生类的正确方法是什么
- 尝试将unique_ptrs推送到向量时使用纯虚拟函数错误
- 有没有比在库中添加一个并非由所有派生类实现的新虚拟函数更好的设计实践
- 类型擦除的std::function与虚拟函数调用的开销
- 重写虚拟函数和继承
- 用纯虚拟函数兜圈子
- 为什么使用存储在虚拟方法表中的地址调用虚拟函数的函数会返回垃圾?
- 禁止子函数调用父级的抽象(或虚拟)函数
- 无法在子类中使用虚拟函数C++
- 无法在派生对象上运行虚拟函数
- 我可以调用从 main() 覆盖的虚拟函数吗?
- 在 C++ 中将函数获取和设置为虚拟函数
- 使用在堆栈上创建的对象调用虚拟函数
- 为什么在这种情况下不调用我的虚拟函数实现?
- 在C++中使虚拟函数私有化
- 模板继承类中的虚拟函数
- 为什么构造函数的虚拟函数调用有时有效,但其他调用却无效
- doxygenc++虚拟函数和实现
- 如何从派生类函数中调用虚拟函数