从类中动态分配的对象数组中删除对象

时间:2016-05-06 08:26:56

标签: c++

我有一个非常简单的问题,但由于我缺乏C ++经验,我似乎无法解决它。我有一个类PlayList,它有一个动态分配的数组作为私有数据成员。我从未使用动态数组,我对如何添加特定对象和删除特定对象感到困惑。我通过引用传递一个Song对象,需要将其删除。我该怎么办?我目前的代码如下(歌曲是一个单独的类,我不包括在内)

#ifndef PROJ5_PLAYLIST_H_INCLUDED
#define PROJ5_PLAYLIST_H_INCLUDED
#include "song.h"
#include <iostream>

class PlayList{

private:
    Song* playList_arr;
    int size_of_playlist;
    int numberOfSongs;
public:

    PlayList();
    ~PlayList();
    void AddSong(const Song& s);
    bool DeleteSong(const Song& s);
    void ShowAll() const;
    void play(int num=1);
    void ShowStatus()const;

};

#endif // PROJ5_PLAYLIST_H_INCLUDED

.cpp文件

  #include <iostream>
#include "proj5_playlist.h"


PlayList::PlayList()
{
    size_of_playlist = 2;
    numberOfSongs = 0;
    playList_arr = new Song[size_of_playlist];
}

PlayList::~PlayList()
{
    delete [] playList_arr;
}

void PlayList::AddSong(const Song& s)
{
    if(numberOfSongs==size_of_playlist){
        Song* arr=new Song[size_of_playlist+1];
        arr[size_of_playlist]=s;
        for(int i=0;i<size_of_playlist;i++)
        {
            arr[i]=playList_arr[i];
        }
        playList_arr=arr;
        delete arr;
        arr = NULL;
    }
    else{
        numberOfSongs++;
        playList_arr[numberOfSongs-1] = s;
    }

}


void PlayList::DeleteSong(const Song& s)
{


}

1 个答案:

答案 0 :(得分:0)

使用标准库对象(例如vector或linkedlist)。 如果您真的想使用动态数组,请尝试以下方法:

void PlayList::DeleteSong(const Song& s)
{
  // First search specified song
  int index;
  for (index = 0; index < numberOfSongs; index++)
  {
    if (playList_arr[index] == s) // You should implement operator==
      break;
  }

  // Maybe not found
  if (index == numberOfSongs)
  {
    ...
    return;
  }

  // Remove song fron array
  while (index < (numberOfSongs-1))
  {
    playList_arr[index] = playList_arr[index+1];
    index++;
  }

  // We got one less song
  numberOfSongs--;

} // DeleteSong