简体   繁体   中英

how can i use a vector in multiple .cpp and header files simultanously?

i have a main.cpp and some classes which each of them is defined in two files: a header and a .cpp file. in the main.cpp i have a 2d vector. I want to use this vector in the member functions of the classes.first i tried to include the main file, but i received the redefinition Error. after that i tried to define the vector in another .h file. but that didn't work either. so what should i do to use this vector in the defining of some classes, in that way that it could save the changes which member functions made.

unfortunately the vector is global!

for more information this vector is board of a game. this game has some objects: a monster, a human, a treasure and some traps. the board is defined global before the main function. there are some functions in main.cpp that use this board, and classes which i mentioned 3 lines above, use this board in their member functions.

is solution using 'extern'?(i don't know what it is, i just saw it in answers!-if it's the solution, i should search about it.)

You may write it like this:

ah

extern vector< vector<int> > vec2D; //declare the 2d vector here

a.cpp

#include "a.h"    
vector< vector<int> > vec2D;  //define the 2d vector here

main.cpp

#include "a.h"
//use the 2d vector here

Main.cpp

#include <vector>

std::vector<std::vector<int>> myArray;

int main(int argc, char **argv)
{
   // blah...
   myArray.add(5);
}

and in your other file:

#include <vector>

extern std::vector<std::vector<int>> myArray;

using the extern keyword allows you to tell the compiler "Hey, this object right here, it doesn't exist... But don't worry! You'll find it once the linker assembles the compiled objects!".

You can also use the " extern " keyword to load serialized data (like bmp2c, which makes a .c file that contains the picture's binary data)

EDIT: Also, it's important that the 2 objects have the exact same name (case sensitive).

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM