我如何访问在头文件中声明并在源文件中填充的主文件中的静态向量变量。实际代码有点大,所以下面是我尝试过的示例。
类.h
class a{
private:
int x;
public:
friend void createVec();
};
void createVec();
static std::vector<a> vec;
源码.cpp
include"class.h"
extern std::vector<a> vec; //if i remove this line code runs and don't show any error
// -of undefined variable
void createVec()
{
for(int i=0; i<9; i++)
{
vec.push_back(i); //while debugging and watching vec, code is able to populate vec
//but i doubt whether is it vector declared in class.h or not
}
}
主文件
#include "class.h"
extern std::vector<a> vec;
int main()
{
createVec();
cout<<vec.size() //it prints 0 instead of 10
}