I'm currently working on a card game, and I'm having trouble with some initialization code:
// in my class...
Card cards[20];
// in method...
for(int i = 0; i <= 20;i++)
cards++ = new Card(i, /*i as char +*/ "_Card.bmp");
The trouble is that my compiler's telling me that cards++
is not an l-value. I've read up on the whole pointer-array equivalence thing, and I thought I understood it, but alas, I can't get it to work. My understanding is that since cards
degrades to a pointer, and the new
operator gives me a pointer to the location of my new instance of Card, then the above code should compile. Right?
I've tried using a subscript as well, but isn't cards+i
, cards++
, and cards[i]
just 3 ways of saying the same thing? I thought that each of those were l-values and are treated as pointers.
One way to initialize the array of objects is by using the constructors. When you create actual objects, you can assign initial values to each of the objects by passing values to the constructor. You can also have a separate member method in a class that will assign data to the objects.
The initializer for an array is a comma-separated list of constant expressions enclosed in braces ( { } ). The initializer is preceded by an equal sign ( = ). You do not need to initialize all elements in an array.
Creating an Array Of Objects In Java – An Array of Objects is created using the Object class, and we know Object class is the root class of all Classes. We use the Class_Name followed by a square bracket [] then object reference name to create an Array of Objects.
Initializing arrays But the elements in an array can be explicitly initialized to specific values when it is declared, by enclosing those initial values in braces {}. For example: int foo [5] = { 16, 2, 77, 40, 12071 };
Card cards[20];
cards
is already an array of objects. They are constructed with the default constructor(constructor with no arguments). There is no need to new
again. Probably you need a member function equivalent to constructor arguments and assign through it.
for ( int i=0; i<20; ++i ) // array index shouldn't include 20
cards[i].memberFunction(/*....*/);
Even simpler is to use std::vector
std::vector<Card> cards;
for( int i=0; i<20; ++i )
cards.push_back(Card(i, /*i as char +*/ "_Card.bmp"); )
The code Card cards[20];
already creates an array of 20 Card
objects and creates them with the default constructor. This may not be what you want given your code.
I would suggest using vector
instead.
std::vector<Card> cards;
for(int i = 0; i < 20;i++)
{
cards.push_back(Card(i, /*i as char +*/ "_Card.bmp"));
}
Note that your for
loop goes from 0
to 20
and thus one past the end of the array.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With