由C++的继承引出来的无法通过编译的问题

C++语言 码拜 9年前 (2015-05-11) 1103次浏览 0个评论

对于我这种对C++特性还不熟悉的新手来说,设计类简直有点找虐。代码如下,基类list里面全都是纯虚函数,派生类seqList里公有继承了list类,但无法通过编译。
这个是基类list的情况:

template <typename elemType>
class list
{
public :
    virtual void clear() = 0;
    virtual int lenght()const = 0;
    virtual void insert(int i, const elemType &x) = 0;
    virtual void remove(int i) = 0;
    virtual int search(const elemType &x)const = 0;
    virtual elemType visit(int i)const = 0;
    virtual ~list(){}
};

这个是基类seqList的情况:
函数具体的实现过程没有写出,因为我觉得问题不在这里

template <typename elemType>
class seqList : public list<elemType>
{
private :
    elemType *data;                          
    int      currentLength;                
    int      maxSize;                           
    void     doubleSpace();                    

public :
    
    seqList(int initSize = 10);
    ~seqList() {delete [] data;}
    void clear() {currentLength = 0;}
    int length()const {return currentLength;}
    void insert(int i, const elemType &x);
    void remove(int i);
    int search(const elemType &x)const;
    elemType visit(int i)const {return data[i];}
    void traverse()const;
};

template <typename elemType>
void seqList<elemType> :: doubleSpace()                 //扩容
{
    ;  
}

template <typename elemType>
seqList<elemType> :: seqList(int initSize)              //顺序表初始化
{
    ;
}

template <typename elemType>                            //在第i个位置插入元素
void seqList<elemType> :: insert(int i, const elemType &x)
{
    ;
}

template <typename elemType>
void seqList<elemType> :: remove(int i)
{
    ;
}

template <typename elemType>
int seqList<elemType> :: search(const elemType &x)const
{
    ;
}

template <typename elemType>
void seqList<elemType> :: traverse()const
{
    ;
}

接下来是对该类进行简单的测试

void testForSeqList()
{
    seqList<int> l;
    cout << "currentLength : " << l.currentLength << endl;
    cout << "maxSize : " << l.maxSize << endl;
    l.insert(1, 1);
    l.insert(1, 2);
    l.insert(1, 3);
    cout << "currentLength : " << l.currentLength << endl;
    cout << "maxSize : " << l.maxSize << endl;
    l.traverse();
    l.remove(1);
    l.traverse();

}

接下来编译器就不干了,报错。这些currentLength, maxSize是私有的,无法访问这就算了。让我无法理解的是:
编译器指着testForSeqList()函数中的seqList<int> l这句说:
cannot declare variable “”l”” to be of abstract type “”seqList<int>”” 
becasue the following virtual function are pure within “”seqList<int>””
这是怎么回事了,请懂的同学给我讲讲!谢谢!

40分
基类里面的 length 拼写错了,你写的是:

virtual int lenght()const = 0;

而派生类里面的是

int length()const {return currentLength;}

这样有一个函数还是纯虚的,就不能实例化了

原来如此,好粗心啊

CodeBye 版权所有丨如未注明 , 均为原创丨本网站采用BY-NC-SA协议进行授权 , 转载请注明由C++的继承引出来的无法通过编译的问题
喜欢 (0)
[1034331897@qq.com]
分享 (0)

文章评论已关闭!