problem with static vector of a class pointer inside the class itself.
-
Hello, I am trying to build a class Matrix which contains a member
vector<Matrix*> vecMat
i.e. the vector of class pointers to the class itself; I want this vector as static so that in each element of the vector(i.e. the class) contains only one copy of this vector. However it is not working. If I do not make this member as static it works fine.
Does any one have idea why is that? why can't I make the vecMat as static.
Any suggestions on this program would be very appreciable.#include<iostream> #include<vector> using namespace std; struct Matrix{ int nrow; int ncol; vector< vector<int > > mat; public: Matrix(int row, int col): nrow(row),ncol(col) { mat.resize(ncol); for(unsigned int i=0;i<mat.size();++i) mat[i].resize(nrow); } static vector<Matrix*> matVec; /* if matVec is not static then this code is working */ ~Matrix(); static void fillUpVectorElement( int x , int y, vector<Matrix*> & pmatVec); }; Matrix::~Matrix() { for (unsigned int i=0;i<matVec.size();++i) delete matVec[i]; //matVec[i]=NULL; } void Matrix:: fillUpVectorElement(int x , int y, vector<Matrix*> & pmatVec) { Matrix* pMatrix=new Matrix (x, y); //.... /*fill up matrix element*/ pmatVec.push_back(pMatrix); } int main (int argc, char**argv){ Matrix MAT (3, 4); return 0;}
-
Static class members must be defined somewhere. A declaration is not enough.
class foo { static int bar; // This ist just a declaration that a variable foo::bar exists }; int foo::bar; // It must be defined somewhere. For example in some foo.cpp
BUT: This sounds like an awful, awful design choice. Why would you ever make elements of a matrix static? What happens if you have two matrices?
-
The error:
main.cpp:(.text+0x1d): undefined reference to `Matrix::matVec'
The solution:
You need to define the static data. Placevector<Matrix*> Matrix::matVec;
outside the class Definition inside your .cpp-file (to satisfy ODR this must not be in the .h)
-
SeppJ schrieb:
Static class members must be defined somewhere. A declaration is not enough.
class foo { static int bar; // This ist just a declaration that a variable foo::bar exists }; int foo::bar; // It must be defined somewhere. For example in some foo.cpp
BUT: This sounds like an awful, awful design choice. Why would you ever make elements of a matrix static? What happens if you have two matrices?
thank you SeppJ, each class object of class Type Matrix contains a vector of Matrix pointer. I need only one vector of class objects but not two or more than two vector of class matrix. but this is a vector of pointer to class obj.so, probably it wont be a problem.
-
But why are you deleting all of those Pointers on every destructor-call? While your program is technically correct it still makes no sense. Whatever you want to achieve here, I am sure you are doing it wrong.