我必须用 stl 为我的数据结构类实现我自己的列表,这是我拥有的代码。
播放列表.h
#ifndef PLAYLIST_H
#define PLAYLIST_H
#include <iostream>
using std::ostream;
#include <list>
using std::list;
class Song;
class Playlist
{
public:
void append(const char* name, const char* artist);
list<Song>::iterator find(const char* name) const;
void delete_song(const char* name);
void print(ostream& out) const;
private:
list<Song> plist;
};
ostream& operator << (ostream& out, const Playlist& playlist);
#endif /* PLAYLIST_H */
ostream& operator << (ostream& out, const Playlist& playlist);
#endif /* PLAYLIST_H */
播放列表.cpp
#include <iostream>
using std::ostream;
using std::endl;
#include <cstring>
#include "Song.h"
#include "Playlist.h"
void Playlist::append(const char* name, const char* artist)
{
Song song(name, artist);
plist.push_back(song);
}
list<Song>::iterator Playlist::find(const char* name) const
{
list<Song>::iterator itr = plist.begin(); // error occurs here
while(itr != plist.end() && strcmp(itr->get_name(), name) == 0)
{
itr++;
}
return itr;
}
void Playlist::delete_song(const char* name)
{
list<Song>::iterator itr = find(name);
if (itr != plist.end())
plist.erase(itr);
}
void Playlist::print(ostream& out) const
{
list<Song>::iterator itr = plist.begin(); // error occurs here
while (itr != plist.end())
{
out << *itr << endl;
itr++;
}
}
ostream& operator << (ostream& out, const Playlist& playlist)
{
playlist.print(out);
return out;
}
当我尝试编译它时,我得到:
错误:请求从 'std::list::const_iterator {aka std::_List_const_iterator}' 转换为非标量类型 'std::list::iterator {aka std::_List_iterator}'
在代码中标记的两个地方。