在我的任务中,我仍然有点卡在另一部分上。
以下是提示的要求:
现在您可以修改LoadMovies函数以创建MovieList 对象并将每个Movie对象添加到它。功能 LoadMovies应该返回一个指向MovieList对象的指针。这意味着 你需要动态地在堆上创建MovieList对象。
更改main函数并将返回的MovieList指针存储在a中 变量。要测试一切是否按预期工作,您可以使用 MovieList对象的PrintAll函数。
到目前为止,这是我的代码:
class MovieList {
public:
Movie* movies;
int last_movie_index;
int movies_size;
int movie_count = 0;
MovieList(int size) {
movies_size = size;
movies = new Movie[movies_size];
last_movie_index = -1;
}
~MovieList() {
delete [] movies;
}
int Length() {
return movie_count;
}
bool IsFull() {
return movie_count == movies_size;
}
void Add(Movie const& m)
{
if (IsFull())
{
cout << "Cannot add movie, list is full" << endl;
return;
}
++last_movie_index;
movies[last_movie_index] = m;
}
void PrintAll() {
for (int i = 0; i < movie_count; i++) {
movies[last_movie_index].PrintMovie();
}
}
};
void ReadMovieFile(vector<string> &movies);
void LoadMovies();
enum MovieSortOrder
{
BY_YEAR = 0,
BY_NAME = 1,
BY_VOTES = 2
};
int main()
{
LoadMovies();
// TODO:
// You need to implement the Movie and MovieList classes and
// the methods below so that the program will produce
// the output described in the assignment.
//
// Once you have implemented everything, you should be able
// to simply uncomment the code below and run the program.
MovieList *movies = LoadMovies();
// // test methods for the Movie and MovieList classes
//PrintAllMoviesMadeInYear(movies, 1984);
//PrintAllMoviesWithStartLetter(movies, 'B');
//PrintAllTopNMovies(movies, 5);
//delete movies;
return 0;
}
void LoadMovies()
{
vector<string> movies;
ReadMovieFile(movies);
string name;
int year;
double rating;
int votes;
for (int i = 0; i < movies.size(); i++)
{
istringstream input_string(movies[i]);
getline(input_string, name, '\t');
input_string >> year >> rating >> votes;
Movie movie (name, year, votes, rating);
movie.PrintMovie();
}
}
现在,我被困在哪里,教授要求我修改提示中的LoadMovies并将其转换为指针。我画的是空白。出于某种原因,如果我尝试编译它说:
C:\Users\Andy\Documents\C++ Homework\MovieStatisticsProgram\MovieStatsProgram.cpp:163: error: void value not ignored as it ought to be
MovieList *movies = LoadMovies();
^
答案 0 :(得分:0)
构造函数的顺序错误
MovieList(int size) {
movies = new int[movies_size]; // movies_size hasn't been initialized yet!
movies_size = size;
last_movie_index = -1;
}
应该是
MovieList(int size)
: movies_size{size}, movies{new int[size]}, last_movie_index{0}
{}
虽然@ ScottMcP-MVP指出你的阵列应该是
Movie* movie;
所以你的建造者将是
MovieList(int size)
: movies_size{size}, movies{new Movie[size]}, last_movie_index{0}
{}
关于开始使用剩余功能的一些建议
Length
函数将返回last_movie_index
当前使用的数量。
IsFull
会检查last_movie_index == movies_size - 1
Add
需要使用last_movie_index
来确定数组中存储电影的元素。
PrintAll
必须从[0]
迭代到[movie_count]
并打印出每个元素。
您的Add
功能看起来像
void MovieList::Add(Movie const& m)
{
if (IsFull())
{
std::cout << "Cannot add movie, list is full" << std::endl;
return;
}
movies[last_movie_index] = m; // assigns a copy to your array
++last_movie_index; // Increment the movie index
}