[英]initialization of data types in a std vector
OK I am currently building a matrix using the std vectors that is meant to have a cell or bacteries on them.好的,我目前正在使用 std 向量构建一个矩阵,该矩阵旨在在其上放置一个细胞或细菌。 Because of this I made a "dead" class to be mother of cell and bacteries.正因为如此,我做了一个“死”类来成为细胞和细菌的母亲。 So in the matrix a case that does not have either of them would be dead.所以在矩阵中,没有它们中的任何一个的情况都会死。
But when I try to build the matrix, by somthing like: world[x][y] = new cell()/world[x][y] = new bacterie();但是当我尝试构建矩阵时,通过以下方式: world[x][y] = new cell()/world[x][y] = new bacterie(); it will not compile.它不会编译。
so my question is, how can I initialize it?所以我的问题是,我该如何初始化它?
this is my code, its on spanish sorry.这是我的代码,它是西班牙语,抱歉。
matrizB[fila-1][columna-1] = new BacteriaM();
matrizB its a矩阵 B 是一个
vector<vector <dead>> matrizB(n);
and BacteriaM is a class that inherits from dead;而 BacteriaM 是一个继承自死者的类; n is defined by the user. n 由用户定义。 (sorry for bad grammar and programing, i'm new to programing) (抱歉语法和编程不好,我是编程新手)
In order to use polymorphism, your matrix element must be a pointer .为了使用多态,你的矩阵元素必须是一个指针。
vector<vector <dead*>> matrizB(n);
You will have to be careful to manage the memory of the elements.您必须小心管理元素的内存。 It might be worth looking at smart pointers ( std::shared_ptr
or std::unique_ptr
-- whichever is more correct).可能值得查看智能指针( std::shared_ptr
或std::unique_ptr
-- 以更正确的为准)。
Hope this helps.希望这可以帮助。
The main issue that you are having is the new
operator.您遇到的主要问题是new
运营商。 I am assuming you are not accustomed to C++ when it comes to creating objects.我假设您在创建对象时不习惯C++ 。 The new
operator for C++ does not simply create an object, but a pointer to an object. C++的new
运算符不只是创建一个对象,而是一个指向对象的指针。 So, you can go matrix[x][y] = cell()
or change to a vector< vector < dead* > >
and follow what @Duthomhas says with selecting smart pointers.因此,您可以使用matrix[x][y] = cell()
或更改为vector< vector < dead* > >
并按照@Duthomhas 所说的选择智能指针。 That way you can better manage memory especially when you are dealing with a vector of vectors.这样您就可以更好地管理内存,尤其是在处理向量向量时。
Note: Watch out for cell()
constructors! 注意:注意cell()
构造函数! C++ will get confused and think you are declaring a function... C++会感到困惑,并认为您在声明一个函数......
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.