错误原因
派生类没有定义所有的基类中的虚函数。
我的问题主要出在基类中虚函数有const关键字,在派生类中对函数定义时,忘了加上const关键字,导致没有覆盖基类中的虚函数。
错误示例
typedef string elemType;
class Stack1{
public:
virtual void push(elemType& a) =0;
virtual elemType pop() = 0;
virtual int size() const=0;
virtual bool empty() const = 0;
virtual bool full() const = 0;
virtual elemType peek() const = 0;
virtual void print() const = 0;
};
class LIFO_Stack:public Stack1{
public:
LIFO_Stack();
LIFO_Stack(vector<elemType> &s):_vec(s){top=s.size()-1;};
int size() {return _vec.size();} //---错误处
bool empty() {return _vec.size();} //---错误处
bool full() {return _vec.size()==max_size;} //---错误处
void push(elemType& a);
elemType pop() {_vec.pop_back();return _vec[top];}
elemType peek() {return _vec[top];}
void print(){
cout<<"栈的元素如下:"<<endl;
int i;
for(i = 0;i<_vec.size();i++)
cout<<this->_vec[i]<<" ";
cout<<endl;
}
protected:
int max_size = 1024;
int top;
vector<elemType> _vec;
};
修改后
typedef string elemType;
class Stack1{
public:
virtual void push(elemType& a) =0;
virtual elemType pop() = 0;
virtual int size() const=0;
virtual bool empty() const = 0;
virtual bool full() const = 0;
virtual elemType peek() const = 0;
virtual void print() const = 0;
};
class LIFO_Stack:public Stack1{
public:
LIFO_Stack();
LIFO_Stack(vector<elemType> &s):_vec(s){top=s.size()-1;};
int size() const {return _vec.size();} //---修改后
bool empty() const {return _vec.size();} //---修改后
bool full() const {return _vec.size()==max_size;} //---修改后
void push(elemType& a);
elemType pop() {_vec.pop_back();return _vec[top];}
elemType peek() const{return _vec[top];}
void print()const{
cout<<"栈的元素如下:"<<endl;
int i;
for(i = 0;i<_vec.size();i++)
cout<<this->_vec[i]<<" ";
cout<<endl;
}
protected:
int max_size = 1024;
int top;
vector<elemType> _vec;
};