我的模型非常简单,但我正在使用的矢量有一些问题。
基本上,我有一个Song类,它有一个播放列表,播放列表可以有多个轨道(在矢量内)。
Song* song = new Song("Rien de rien", "Biggy", 120);
Playlist* playlist;
Track* synthTrack;
playlist->addTrack(synthTrack); // without this line everything works fine
song->setPlaylist(playlist);
cout << "Title " + song->getTitle() << endl;
控制台没有给我任何错误,但cout
没有显示。只要我将曲目添加到播放列表,就会发生这种情况。
这就是我的播放列表类:
class Playlist {
private:
vector<Track*> tracklist;
public:
void addTrack(Track* track){
this->tracklist.push_back(track);
}
};
答案 0 :(得分:4)
您正在通过访问无效指针来调用未定义的行为,这意味着任何事情都可能发生:
Playlist* playlist;
Track* synthTrack;
playlist->addTrack(synthTrack); // using uninitialized pointer
应该是
Playlist* playlist = new Playlist; //initialize playlist here
Track* synthTrack = new Track; //also initialize synthTrack
playlist->addTrack(synthTrack);
答案 1 :(得分:3)
Song song("Rien de rien", "Biggy", 120);
Playlist playlist;
Track synthTrack;
playlist.addTrack(synthTrack);
song.setPlaylist(playlist);
cout << "Title " << song.getTitle() << "\n";
...和
class Playlist {
vector<Track> tracklist;
public:
void addTrack(Track const &track){
tracklist.push_back(track);
}
};
需要指针是非常不寻常的,当你确实需要它们时,你几乎肯定想要将它们包装在某种智能指针类中。在这种情况下,我没有看到后者是必要的,甚至可能是有用的。
答案 2 :(得分:2)
class Playlist
{
private:
vector<Track> tracklist;
public:
void addTrack(const Track& track){
tracklist.push_back(track);
}
};
Song song("Rien de rien", "Biggy", 120);
Playlist playlist;
Track synthTrack;
playlist.addTrack(synthTrack);
song.setPlaylist(playlist);
cout << "Title " + song.getTitle() << endl;
或者如果你想避免复制使用std :: unique_ptr或std :: shared_ptr