c++ - 编译器说定义的函数是虚拟的

标签 c++ operator-overloading pure-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);
}

最佳答案

operator==stackADT采用 const stackADT<Type>& 类型的参数, operator==stackType采用 const stackType<Type>& 类型之一.由于它们具有不同的签名,因此它们具有不同的功能。

如果您想确保派生类中的函数覆盖基类中的函数,您可以(在 C++11 中)使用 override关键词。如果你的函数没有覆盖任何东西,它会让编译器报错。

就目前而言,您的抽象基类要求每个派生类都可以与基类进行比较。因此,您可以仅根据基础中可用的成员进行比较。由于比较应该是可传递的,这也意味着可以仅根据基类中存在的成员来比较不同的派生类。如果这不是您想要的,您应该从基地中移除运算符(operator)。

关于c++ - 编译器说定义的函数是虚拟的,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46800685/

相关文章:

C++ 并将枚举值写入 Windows 注册表

c++ - 在没有重载的情况下在 Union 上进行类型转换重载 +=

C++,菱形继承(钻石问题),何时/何地需要实现纯虚拟?

c++ - 在 C++ 中,如何返回采用纯虚拟(const ref)参数的对象?

c++ - 在 WINPCAP 中如何知道哪些安装的设备有互联网连接?

c++ - C++ 结构可以转换为 Microsoft Bond 结构吗?

模板类上的 C++ 运算符重载

c++ - 具有未重写的纯虚拟析构函数的类是否应该可初始化?

c++ - Xerces/Xalan : UNC path as argument for document function?

C++ 运算符与友元重载