Невозможно объявить поле как абстрактный тип из вложенных шаблонов - PullRequest
0 голосов
/ 19 сентября 2018

Я пытаюсь создать абстрактный список воспроизведения, используя классификатор, использующий шаблон 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_*/

и, наконец, Playlist.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 голосов
/ 19 сентября 2018

Именно поэтому ключевое слово override было введено в C ++ 11.Вы не переопределили свои методы, потому что const указанный пропущен.

Добавьте в производный класс:

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

и увидите ошибку.Затем измените на:

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

и посмотрите снова.Добавьте const ко всем методам, где это необходимо.Если у вас есть в базовом классе const - квалифицированный член, вам нужно указать const и в производном классе.

...