static vector in a class

Started by
4 comments, last by shishio 17 years, 11 months ago
I get a linker error (LNK2001) when trying to compile this under ms visual c++ 6.0. Is it possible to declare static vector containers in a class? #include <vector> using std::vector; class a { private: static vector<int> b; public: //other functions }; Any idea what's wrong? Thanks.
Advertisement
Static data members must be defined as well as declared. You only have a declaration. You need to add vector< int > a::b; to a cpp file at global/namespace scope. Also you shouldn't use using declarations in a header file. Instead fully qualify the names (i.e. std::vector< int >). And for the love of all things code update your compiler to something which actually supports modern C++.

Σnigma
That would work if I were defining constant elements of the vector array, for example:

vector<int> a::b[0] = 5;

But what if I were defining an unknown number of elements in a function and wanted to store them in a vector, like:

void a::numbers()
{
int end = 0;
cin >> end;
for(int i = 0; i < end; i++)
b.push_back(i);
}

How would I make a function like this work?
a.h
#include <vector>// class definitionclass a{	private:		// static data member declaration		static std::vector< int > b;	public:		// static member function declaration		static void numbers();};

a.cpp
#include "a.h"#include <iostream>using std::cin;// static data member definitionstd::vector< int > a::b;// static member function definitionvoid a::numbers(){	int end = 0;	cin >> end;	for (int i = 0; i < end; ++i)	{		b.push_back(i);	}}

Σnigma
No, that's not what he said at all.

When you write:

class a{private:static vector<int> b;


That DOES NOT CREATE the vector of ints. It just says that the name 'b' will refer to a vector of ints declared somewhere else. Sad but true. You fix this by adding such a declaration:

// at global or namespace scope in a .cpp filevector< int > a::b;


Note that the statement "vector<int> a::b[0] = 5;" is not going to compile. When you write "vector<int>", the compiler expects the next thing to be a variable name, which means "a::b[0]" gets interpreted as "the name b in class a, which is an array of zero vectors of int". That doesn't match the declaration -> compiler barfs. When you want to actually assign to a::b[0], you would not write the type name again.

(By the way, the fact that you seem to want to append to a static vector of int from a member function is a bit suspicious. What are you trying to do?)
Thanks for the fast replies. I got the static vector to work properly, and the program works fine.

This topic is closed to new replies.

Advertisement