C ++程序从打印功能崩溃

时间:2014-12-05 23:27:36

标签: c++

目前我的程序在250中显示一行之后崩溃,它应该显示。这是我的代码:

string MovieList::PrintAll() {
   for (int i = 0; i < last_movie_index; i++) {
        movies[last_movie_index].Movie::PrintMovie();
   }
}

string Movie::PrintMovie() {
    cout << fixed << setprecision(1) << rating << "\t\t" << votes << "\t\t" << "(" <<
            year_made << ")" << "\t" << name << endl;
}

Full Movie和MovieList类:

class Movie {
public:
    Movie();
    Movie(string n, int y, int v, double r);
    string get_name();
    void set_name(string n);
    int get_year();
    void set_year(int y);
    int get_votes();
    void set_votes(int v);
    double get_rating();
    void set_rating(double r);
    string PrintMovie();

private:
    string name;
    int year_made;
    int votes;
    double rating;

};

Movie::Movie() {
    name = "null";
    year_made = 0;
    votes = 0;
    rating = 0.0;
}

Movie::Movie(string n, int y, int v, double r) {
    name = n;
    year_made = y;
    votes = v;
    rating = r;
}

string Movie::get_name() {
    return name;
}

void Movie::set_name(string n) {
    name = n;
}

int Movie::get_year() {
    return year_made;
}

void Movie::set_year(int y) {
    year_made = y;
}

int Movie::get_votes() {
    return votes;
}

void Movie::set_votes(int v) {
    votes = v;
}

double Movie::get_rating() {
    return rating;
}

void Movie::set_rating(double r) {
    rating = r;
}

string Movie::PrintMovie() {
    cout << fixed << setprecision(1) << rating << "\t\t" << votes << "\t\t" << "(" <<
            year_made << ")" << "\t" << name << endl;
}

class MovieList {
public:
    MovieList(int size);
    ~MovieList();
    int Length();
    bool IsFull();
    void Add(Movie const& m);
    string PrintAll();

private:
    Movie* movies;
    int last_movie_index;
    int movies_size;
    int movie_count = 0;

};

MovieList::MovieList(int size) {
    movies_size = size;
    movies = new Movie[movies_size];
    last_movie_index = -1;
}

MovieList::~MovieList() {
    delete [] movies;
}

int MovieList::Length() {
    return last_movie_index;
}

bool MovieList::IsFull() {
    return last_movie_index == movies_size;
}

void MovieList::Add(Movie const& m)
{
    if (IsFull()) {
        cout << "Cannot add movie, list is full" << endl;
        return;
    }
    last_movie_index++;
    movies[last_movie_index] = m;
}

string MovieList::PrintAll() {
   for (int i = 0; i < last_movie_index; i++) {
        movies[i].Movie::PrintMovie();
   }
}

我的数组电影是动态分配的(即movies = new Movie[movies_size];)。我注意到使用cout << movies[1] << endl在PrintAll函数中不起作用。这可能是它崩溃的原因吗?我该怎么做才能解决它?

1 个答案:

答案 0 :(得分:0)

这不会解决您的问题,但是如果您想让cout << movies[i] << endl工作,那么您需要在Movie类中定义以下函数:

friend ostream& operator<<(ostream& ostr, const Movie& movie){
    ostr << fixed << setprecision(1) << rating << "\t\t" << votes << "\t\t" << "(" <<
            year_made << ")" << "\t" << name ;
}