无法从嵌套模板中声明字段为抽象类型

时间:2018-09-19 06:23:29

标签: c++ class templates abstract-class

我正在尝试使用限定符使用模板setInterface.h制作一个抽象播放列表,并设置Set.h,Playlist.h和Song.h。

在我添加Playlist.h之前,一切正常,直到出现“错误:无法将字段'PlayList :: playlist_'声明为抽象类型'Set'”。

代码如下:

SetInterface.h

    #ifndef SET_INTERFACE_H_

    #define SET_INTERFACE_H_

    #include <vector>

    template<class ItemType>

    class SetInterface{

    public:

       /** Gets the current number of entries in this set.
    */
       virtual int getCurrentSize() const = 0;

       /** Checks whether this set is empty.
    */
       virtual bool isEmpty() const = 0;

       /** Adds a new entry to this set.
    */
       virtual bool add(const ItemType& newEntry) = 0;
       /** Removes a given entry from this set,if possible.

    */
       virtual bool remove(const ItemType& anEntry) = 0;

       /** Removes all entries from this set.
    */
       virtual void clear() = 0;

       /** Tests whether this set contains a given entry.
    */
       virtual bool contains(const ItemType& anEntry) const = 0;

       /** Fills a vector with all entries that are in this set.
    */
       virtual std::vector<ItemType> toVector() const = 0; 

    }; // end SetInterface

    #endif /* SET_INTERFACE_H_ */

Set.h

#ifndef Set_H_

#define SET_H_
#include "SetInterface.h"

template <class ItemType> 
class Set: public SetInterface<ItemType>{
    public:
    Set();
        //Overriding SetInterface functions

    int getCurrentSize();

    bool isEmpty();

    bool add(const ItemType& newEntry);

    bool remove(const ItemType& anEntry);

    void clear();

    bool contains(const ItemType& anEntry);

    std::vector<ItemType> toVector();

    private:
    static const int DEFAULT_SET_SIZE = 4; // for testing purposes we will keep the set small

    ItemType items_[DEFAULT_SET_SIZE]; // array of set items

    int item_count_;                  // current count of set items

    int max_items_;    // max capacity of the set

    // post: Either returns the index of target in the array items_
    // or -1 if the array does not contain the target
    int getIndexOf(const ItemType& target) const;
};

#endif /*SET_H_*/

最后是播放列表。h

#ifndef PLAYLIST_H_
#define PLAYLIST_H_
class PlayList: public Set<Song>{//inherits Set with Song replacing ItemType
    public:
    PlayList();
    PlayList(const Song& a_song);

    private:
    Set<Song> playlist_;//error: cannot declare field 'PlayList::playlist_' to be of abstract type 'Set<Song>'
};

#endif /*PLAYLIST_H_*/  

Set.h和PlayList.h是通过它们各自的cpp文件定义的,但这似乎与我实现playList类有关。据我了解,Set模板类定义了SetInterface类中的所有虚函数(通过Set.cpp文件),没有问题,但是我仍然不能声明Set对象吗?我很茫然。

非常感谢您一如既往的帮助。

1 个答案:

答案 0 :(得分:2)

这就是为什么C ++ 11中引入了override关键字的原因。您没有覆盖方法,因为缺少指定的const

添加派生类:

std::vector<ItemType> toVector() override;

并查看错误。然后更改为:

std::vector<ItemType> toVector() const override;

,然后再次查看。将const添加到所有需要的方法中。如果您具有const合格的基类成员,则还需要在派生类中提供const

相关问题