kungfuelmosan wrote:
Hey guys, Im just getting into c++ at the moment so please bare with
me
Basically i need to declare a vector<stringstringArray(50)
inside a class, however by doing so i am getting the following error:
error: expected identifier before numeric constant
error: expected ';' or '...' before numeric constant
But i can declare vector<stringtestArray(50); inside my main
function or a method function etc fine? it seems like i cant specify
the (50) to make it an array
My code is something like this:
#include <vector>
#include <string>
using namespace std;
class testClass {
vector<stringtestArray(50);
}
The type you actually have to use is vector<string>. Note that this type is
designed to work without prior knowledge about the number of elements that
should be stored inside it. So, in contrast to array declarations, you don't
have to (and cannot) specify the number of elements you want to use. Your member
must thus be declared so:
class testClass {
vector<stringtestArray;
}
The statement
vector<stringtestArray(50);
is both a declaration of a variable and an initialization: The constructor
std::vector::vector (size_type _N, [+other parameters with default values])
is called. In class declarations you are only allowed to _declare_ things, you
must not try to _initialize_ them (initialization of members is what
constructors are for).
If you already know that your class only ever needs to hold 50 strings, you can
use a plain array of strings:
class testClass {
string testArray[50];
}
Note that we use square brackets in this _declaration_ of an array type. It may
be a bit confusing that the number of elements are put after the variable name,
so that this declaration looks similar to "vector<stringtestArray(50);",
but actually the "[50]" part belongs to the type of the variable. It would be
more obvious if we had to write "string[50] testArray;", but this doesn't work
in C++ (for historical reasons).
Another way would be do initialize your vector of strings in the constructor:
class testClass {
vector<stringtestArray;
testClass ();
}
testClass::testClass ()
: testArray (50)
{
// Now testArray will have 50 entries.
}
Regards,
Stuart