對於我的任務,我仍然有點卡在另一部分。C++將元素添加到數組並將函數修改爲指針
這裏有什麼提示,詢問:
現在你可以修改LoadMovies函數創建一個MovieList 對象並添加每個電影的反對它。函數 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();
^
當我做函數原型時,我的編譯器總是會說函數不能被重載,並且函數被超標。 – andayn 2014-12-05 20:59:53
如果你定義了'class MovieList {...}'以外的函數,那麼他們需要這個範圍, 'MovieList :: IsFull()'。如果您在類範圍內定義它們,則它們不會'class MovieList {bool IsFull(); }'請注意,在我上面的例子中,在寫'Length'和'IsFull'的定義之前,我關閉了'class MovieList'的大括號。 – CoryKramer 2014-12-05 21:01:28
此外,在我的LoadMovies函數中,當我添加MovieList :: Add(movie)時,編譯器會說它不能在沒有對象的情況下調用,但是不是已經在參數中的對象? – andayn 2014-12-05 21:05:13