如何将对象添加到类中的静态向量
How to add an object to a static vector within a class
我正在用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();
请注意在类型后添加&
以将其从值更改为引用。
相关文章:
- C++从另一个类访问公共静态向量的正确方法是什么
- 如何从静态向量访问类元素?
- 如何将对象添加到类中的静态向量
- 使用 C++98 标准填充二维静态向量
- C++ 入门 12.1:我可以在类中使用静态向量成员实现 StrBlob<string> 吗?
- DLL – 在 DLL 初始化时填充的静态向量,向客户端程序返回零大小
- 如何通过参考传递向量的静态向量
- 无法在 c++ 中初始化静态向量
- C++类中的静态向量
- C++将局部变量添加到静态向量而不复制
- C :如何在类内声明一个空的私人静态向量
- 如何在运行时才知道c++静态向量大小时指定该大小-不需要
- 在C++类中找不到静态向量
- 静态向量的大小
- 在push_back到静态向量之后C++取消定位
- 如何在静态函数中使用静态向量
- 作为类对象容器的静态向量
- 类层次结构中所有对象的静态向量 shared_ptr
- 如何初始化静态向量成员
- 在元素自己的析构函数中擦除指向静态向量中元素的指针