我正在尝试创建一个MovieList类,该类包含动态分配的double []的weeklyRevenue。我一直收到此错误,我知道它与内存分配有关,但不确定具体细节。我怎样才能解决这个问题?
class Movie
{
public:
Movie();
void setMovieData(char [],char [],char, int,int,int,int,double[]);
~Movie();
string getTitle() const;
char getGenre() const;
void display() const;
double getBoxOffice();
private:
char title[75];
char director[50];
char genre;
Date releaseDate;
double* weeklyRevenue;
double* weeklyTake;
int numWeeks;
};
class MovieList
{
public:
MovieList(); //constuctor
~MovieList(); //deconstructor
int getCapacity();
int getCurrentSize();
void addMovie(char[], char[], char, int ,int, int,int, double[]);
void insertMovie(Movie, int);
void deleteMovie(char []);
void displayList() const;
void displayByGenre(char) const;
int search(char []) const;
Movie* movieListObj;
private:
int capacity, currentSize;
}
movieList.cpp:
void Movie::setMovieData(char t[], char dir[], char g, int month, int day, int year,int numWks, double wklyTake[])
{
for(int i =0; i < 75; i++)
title[i] = t[i];
for (int i = 0; i < 50; i++)
director[i] = dir[i];
genre = g;
releaseDate.setDate(month,day,year);
numWeeks = numWks;
weeklyRevenue = new double[numWeeks];
wklyTake = new double[numWeeks];
for (int i = 0; i < numWeeks; i++)
weeklyRevenue[i] = wklyTake[i];
}
Movie::~Movie()
{
delete [] weeklyTake;
weeklyTake = NULL;
delete [] weeklyRevenue;
weeklyRevenue = NULL;
}
void Movie::display() const
{
cout<<"Title: ";
for(int i =0; i < 75; i++)
cout<< title[i];
cout << "\nDirector: ";
for (int i = 0; i < 50; i++)
cout << director[i];
cout << "\nGenre:" << genre<<endl;
cout << "Release Date: ";
releaseDate.print();
cout<<"Weeks since Release: " << numWeeks<<endl;
cout <<"Box office: " ;
double BoxOffice = 0;
for(int i =0; i <numWeeks; i++)
BoxOffice += weeklyRevenue[i];
cout << BoxOffice;
}
MovieList::MovieList()
{
capacity = 5;
currentSize = 0;
movieListObj = new Movie[currentSize];
}
MovieList::~MovieList()
{
delete [] movieListObj;
movieListObj = NULL;
}
void MovieList::addMovie(char t[], char dir[], char g, int month, int day, int year, int numWeeks, double* weeklyRevenue)
{
if( currentSize >= capacity)
{
capacity += 5;
}
movieListObj[currentSize].setMovieData(t, dir, g, month, day, year, numWeeks, weeklyRevenue);
currentSize++;
}
void MovieList::insertMovie(Movie movieList, int position)
{
if(position < 0 || position > capacity)
cout << "insert failed";
else
{
movieListObj[position] = movieList;
cout << "Insert successful";
}
}
void MovieList::deleteMovie(char titleDel[])
{
for( int i= 0; i < currentSize; i++)
{
while( titleDel == movieListObj[i].getTitle())
cout<< "Delete" ;
}
}
我正在尝试添加电影,但是一旦我在addMovie函数中输入所有数据,就会收到错误消息:“抛出'std :: bad_alloc'实例后终止调用 what():std :: bad_alloc 中止”