c++ class array initialization
so I have this class in the header
class C{
int b [2];
init();
}
and in C.cpp I hav开发者_Python百科e
C::init(){
bK [2] = {3,7};
}
whereby I try to initialize the class variable b which is an array
but then the compiler returns the error expected ; before { token
and expected primary expression before { token
what did i do wrong and how do I properly initialize array class variables?
End your class definition with a ;
.
class C {
int b [2];
init();
};
Also, you cannot initialize an array like that away from the declaration in standard C++.
You can't do this in pre-C++0x C++.
That isn't allowed by the Standard (2003). Arrays declared in class cannot be initialized.
What you can do is this:
C::init(){
b[0] = 3;
b[1] = 7;
}
In C++0x, you can do this (if you choose to use std::vector
):
class C
{
std::vector<int> b;
void init()
{
b = {3,7};
}
};
See online demo : http://www.ideone.com/NN5aT
C::init(){
bK [0] = 3;
bk [1] = 7;
}
You should declare you class members as either public, private or protected. And also you need a return type for you init(). You also might need a semicolon at the end of your class definition, which you can't do with c++ class members.
You should use a constructor instead of your init(). That way you don't have to call init() after every time you declare an object, it will be done for you.
class C{
private:
int b[2];
public:
C();
};
C::C()
{
b[0] = 2;
b[1] = 3;
}
Edit: After doing some testing, I found it was buggy. This code above has no errors in it. If you want to inline initialize a whole array, it has to be done in its declaration statement.
精彩评论