OK I am currently building a matrix using the std vectors that is meant to have a cell or bacteries on them. 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(); 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
vector<vector <dead>> matrizB(n);
and BacteriaM is a class that inherits from dead; n is defined by the user. (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).
Hope this helps.
The main issue that you are having is the new
operator. I am assuming you are not accustomed to C++ when it comes to creating objects. The new
operator for C++ does not simply create an object, but a pointer to an object. So, you can go matrix[x][y] = cell()
or change to a vector< vector < dead* > >
and follow what @Duthomhas says with selecting smart pointers. That way you can better manage memory especially when you are dealing with a vector of vectors.
Note: Watch out for cell()
constructors! C++ will get confused and think you are declaring a function...
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.