C ++:错误:“ {”令牌

时间:2018-09-23 04:24:22

标签: c++ inheritance

我有一个ADT class Set,它继承了其父模板class SetInterface的方法。I also have类Song and类PlayList , which essentially inherits the对应于{{1} }公众成员。我收到以下错误:

class Set

我看到了具有类似问题的线程,并尝试了以下建议:

  1. 检查以确保我的护卫队拼写正确
  2. 将我的文件包含在 .cpp 中,而不是 .hpp 文件
  3. 包括该类,而不是使用In file included from Song.cpp:7:0: Set.h:12:33: error: expected class-name before ‘{’ token class Set : public SetInterface {.
  4. 使用循环包含

但是,我仍然遇到相同的错误,或者对于其他文件它再次出现。因此,我决定创建自己的帖子。这是每个文件的代码:

  1. SetInterface.h

    #include "className.h"
  2. Set.h

    #ifndef SET_INTERFACE_H_
    
    #define SET_INTERFACE_H_
    
    #include <vector>
    
    template<class ItemType>
    
    class SetInterface
    
    {
    
     public:
    ...
    }; // end SetfInterface
    
    #endif /* SET_INTERFACE_H_ */
    
  3. Set.cpp

    #ifndef SET_H_
    
    #define SET_H_
    
    template <class ItemType>
    class Set : public SetInterface {
    
    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
    
     int getIndexOf(const ItemType& target) const;
    
    };
    
    #endif
    
  4. Song.h

    #include "Set.h"
    #include "Song.h"
    
     template<class ItemType>
     class Set : SetInterface {
     public:
     ...
    };
    
  5. Song.cpp

    #include <string>
    
    class Song {
    
    public:
    ...
    };
    
  6. 播放列表.h

    #include "Set.h"
    #include "Song.h"
    #include <string>
    #include <iostream>
    //Default constructor for Song which initializes values
    Song::Song() {
      std::string title_;
      std::string author_;
      std::string album_;
     }
    ...
    }
    
  7. PlayList.cpp

    class PlayList : public Set {
    public: 
    
      PlayList();
    
      PlayList(const Song& a_song);
      int getNumberOfSongs() const;
    
      bool isEmpty() const;
    
      bool addSong(const Song& new_song);
    
      bool removeSong(const Song& a_song);
    
      void clearPlayList();
    
      void displayPlayList() const;
    
     private: 
    
        Set<Song> playlist_;
    }
    

    如何纠正此错误?

1 个答案:

答案 0 :(得分:1)

由于SetInterface是模板类,因此从其继承时需要指定模板参数:

#ifndef SET_H_

#define SET_H_

template <class ItemType>
class Set : public SetInterface<ItemType> {

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

 int getIndexOf(const ItemType& target) const;

};

#endif