如何将对象添加到类中的静态向量

How to add an object to a static vector within a class

本文关键字:静态 向量 对象 添加      更新时间:2023-10-16

我正在用c ++制作一个简单的程序,让用户输入带有他的名字,类别和评级的电影。我创建了两个类,第一个类是电影类。这个类有一个构造函数,可以使用我之前说过的属性(名称、类别、评级(实例化一个新的 Movie 对象。然后我有第二堂课叫电影。在此类中,我想将每个 Movie 对象添加到静态向量,然后对它们进行操作。

问题是,当我尝试将 Movie 对象添加到向量时,它似乎跳过了添加它的部分。 在其他方法 findMovie(( 中,当我遍历这个向量时,它返回的是空的。

那么,如果现在不正确,我该如何正确创建静态向量,以及如何将 Movie 对象添加到该向量中。

这是代码:

电影 HPP:

#ifndef MOVIE_HPP_
#define MOVIE_HPP_
#include <string>
#include <vector>
#include <iostream>
class Movie{
private:
std::string name;
std::string rating;
std::string category;
int id;
static int MoviesCreated;
friend class Movies;
public:
//Constructor
Movie(std::string, std::string, std::string, int, int);
Movie(std::string, std::string, std::string, int);
Movie();
//Copy constructor
Movie(const Movie &);
//Destructor
~Movie(void);
//Methods
std::string getName(void) const;
std::string getRating(void) const;
std::string getCategory(void) const;
int getLike(void) const;
int getId(void) const;
static int getMoviesCreated(void);
};

电影.hpp:

#ifndef MOVIES_HPP_
#define MOVIES_HPP_
#include <string>
#include <vector>
#include "Movie.hpp"
class Movies{
private:
friend class Movie;
static std::vector <Movie> moviesCollection;
public:
void addMovie(Movie);
void deleteMovie(std::string);
Movie * findMovie(std::string);
static std::vector <Movie> getCollection();
};

#endif

电影.cpp:

#include "Movies.hpp"
std::vector <Movie> Movies::moviesCollection;
std::vector <Movie> Movies::getCollection(void){
return moviesCollection;
}
void Movies::addMovie(Movie m){
Movies::getCollection().push_back(m);
}

该方法添加电影,不添加电影。

这就是我在函数内部的 main 中实现它的方式。

void enterMovie(void){
string name, rating, category;
int like,c;
cout << "Enter the name: ";
getline(cin, name);
cout << "Enter the rating: ";
getline(cin, rating);
cout << "Enter the category: ";
getline(cin, category);
cout << "Enter a calification between 1-10 to rate this movie: ";
cin >> like;
if((c= getchar()) =='n') c+=c;
Movie Mov(name, rating, category, like);
cout << "Movie entered: n";
display(Mov);
collections.addMovie(Mov);
}

"集合"是我全局创建的电影对象。

Movies collections;
int main(){

该问题需要同时使用这两个类。

我最近正在学习C ++,所以对这段代码的每一次改进都会非常有帮助

getCollection返回当前集合的副本。由于要修改集合,因此应返回一个引用:

static std::vector<Movie> &getCollection();

请注意在类型后添加&以将其从值更改为引用。