我的工作还停留在另一部分。
这是提示要求的内容:
现在,您可以修改LoadMovies函数以创建MovieList
对象,并向其中添加每个Movie对象。功能
LoadMovies应该返回一个指向MovieList对象的指针。那意味着
您需要在堆上动态创建MovieList对象。
更改主函数并将返回的MovieList指针存储在
变量。要测试一切是否按预期进行,您可以使用
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();
^
最佳答案
您的构造函数顺序错误
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
}