Wu said:
Wu wrote:
Hi there,
I was wondering whether there is a way to use array initializer syntax to
initialize a non-static array member in a class in C++. In particular, if
I have a class Foo:
class Foo {
double arr[2];
}
How can I use C-like array intializer syntax:
double arr[2] = {1,2}
for the class?
Any help is appreciated.
--Peter
You cannot use that syntax with non-static members unless the data is
public and there are no constructors. Of course, constructors are to be
preferred (cf.
http://www.parashift.com/c++-faq-lite/ctors.html). Also,
arrays are evil
(
http://www.parashift.com/c++-faq-lite/containers.html#faq-34.1). See
this post for two similar methods for initializing std::vectors
instead:
http://groups.google.com/group/comp.lang.c++/msg/e2fe5982913d4414
Cheers! --M
Then basically I cannot have a non-static const array member in a class in C++? For example,
class Foo {
const double arr[2];
}
A 'const' array has to be intialized using initializer and a 'const'
non-static member requires a class to have a constructor. And then with
the information you gave, you really cannot have a non-static const
array member in a class in C++.
Is this right? Thanks!
Please put your response below the text you are responding to.
Top-posting is considered impolite. (I fixed it here.)
You are correct that you cannot do that innately. You could, however,
get around the limitation by using a const std::vector as in my
previously cited post or by using a boost::scoped_array and the
appropriate initializer like that given in the previously cited post.
Cheers! --M