Jump to content

Problems with array of class

- - - - -

  • Please log in to reply
6 replies to this topic

#1
Rei_NERV

Rei_NERV

    Newbie

  • Members
  • PipPip
  • 28 posts
Hello everyone, I'm having a huge problem creating arrays of classes, no matter if they contain constructors with or without arguments.

This is my lovely code:

#include <allegro.h>

#include <stdio.h>

#include "image.h"

#include "gameinit.h"

#include "bullet.h"


int main(void)

{

	Game initialize(false);

	

	/*------------INT,CHAR,BOOL INIT--------------*/

		char currKey = ' '; char prevKey = currKey;

		bool collState = false; bool prevCollState = collState;

		bool canshoot = true;

		int score = 0;

	/*------------END OF INITIALIZATION-----------*/

	

	/*------BITMAP,MIDI,SAMPLE,BULLET,IMAGE INIT-------*/

		Image starfield1("stars.bmp");		Image starfield2("stars.bmp");

		Image sky1_1("sky1.bmp");	Image sky1_2("sky1.bmp"); 

		Image sky2_1("sky2.bmp");	Image sky2_2("sky2.bmp"); 

		Image fireball("fireball.bmp");

		BITMAP *screens = load_bitmap("screens.bmp",NULL);

		BITMAP *buffer = create_bitmap(640,480);

		Image player("ship.bmp");

		Image enemy("enemy.bmp");

		Bullet bullet[MAXBULLETS](player);

	/*-------------END OF INITIALIZATION---------------*/

	

	/*----------SPRITE VARIABLES/LOCATIONS INIT----------*/

		player.x = 70; player.y = 320;	enemy.x = 640;

		starfield1.x = 0;	starfield2.x = 640;

		sky1_1.x = 0;	sky1_2.x = 640;

		sky2_1.x = 0;	sky2_2.x = 640;

	/*-------------------END OF INIT---------------------*/

	

	/*-------------------GAME LOOP-----------------------*/

		while(!key[KEY_ESC])

		{

			prevKey = currKey;

			prevCollState = collState;

			/*-----INPUT LOOP-----*/

				while(speed_c>0)

				{

					/*--------BEGIN STARS--------*/

						/*---BACKGROUND STARFIELD MOVEMENT---*/

						if(starfield1.x>-640)

							starfield1.x-=10;

						else if(starfield1.x==-640)

							starfield1.x=640;

						if(starfield2.x>-640)

							starfield2.x-=10;

						else if(starfield2.x==-640)

							starfield2.x=640;


						/*-----FOREGROUND STARS MOVEMENT-----*/

						if(sky1_1.x>-640)

							sky1_1.x-=2;

						else if(sky1_1.x==-640)

							sky1_1.x=640;

						if(sky1_2.x>-640)

							sky1_2.x-=2;

						else if(sky1_2.x==-640)

							sky1_2.x=640;


						/*-------MIDDLE STARS MOVEMENT-------*/

						if(sky2_1.x>-640)

							sky2_1.x-=5;

						else if(sky2_1.x==-640)

							sky2_1.x=640;

						if(sky2_2.x>-640)

							sky2_2.x-=5;

						else if(sky2_2.x==-640)

							sky2_2.x=640;

					/*---------END STARS---------*/

					

					/*-------PLAYER MOVEMENT-------*/

						if(key[KEY_UP])

							if(player.y<71)

								player.y=70;

							else

								player.y-=5;

						else if(key[KEY_DOWN])

							if(player.y+64>410)

								player.y=411-64;

							else

								player.y+=5;

					/*----END OF PLAYER MOVEMENT---*/


					/*====SHOOTING====*/

						if(key[KEY_SPACE])

						{

							for(int i = 0; i < MAXBULLETS; i++)

							{

								if(bullet[i].exist==false && canshoot == true)

								{

									bullet[i].x = player.x+64;

									bullet[i].y = player.y+32;

									bullet[i].shoot(fireball,buffer);

									canshoot = false;

								}

							}

						}

						else if(!key[KEY_SPACE])

						{

							canshoot = true;

						}

						for(int i=0; i<MAXBULLETS; i++)

						{

							if(bullet[i].exist == true)

							{

								bullet[i].movebullets(fireball,buffer);

							}

						}

					/*==END OF SHOOTING==*/

					

					speed_c--;

				}

			/*----END OF INPUT----*/

			

			/*-----------DRAW BLOCK------------*/

				draw_sprite(buffer,screens,0,0);

				textprintf_ex(buffer,font,8,448,makecol(255,0,0),-1,"Score:%i    prevKey:%c    currKey:%c    prevCollState:%c    collState:%c",

					score,prevKey,currKey,prevCollState,collState);

				textprintf_ex(buffer,font,8,458,makecol(0,225,255),-1,"player.x:%i    player.y:%i    starfield1.x:%i    starfield2.x:%i",

					player.x,player.y,starfield1.x,starfield2.x);

				textprintf_ex(buffer,font,8,468,makecol(0,255,0),-1,"sky1_1.x:%i    sky1_2.x:%i    sky2_1.x:%i    sky2_2.x:%i",

					sky1_1.x,sky1_2.x,sky2_1.x,sky2_2.x);

				blit(buffer,screen,0,0,0,0,640,480);

			/*-------END OF DRAW BLOCK---------*/

			clear_bitmap(buffer);

		}

	/*--------------END OF GAME LOOP---------------------*/

	


	

	/*--------------DESTROY INIT---------------*/

		destroy_bitmap(buffer);

		destroy_bitmap(starfield1.sprite);	destroy_bitmap(starfield2.sprite);

		destroy_bitmap(sky1_1.sprite);	destroy_bitmap(sky1_2.sprite);

		destroy_bitmap(sky2_1.sprite);	destroy_bitmap(sky2_2.sprite);

		destroy_bitmap(screens);	destroy_bitmap(fireball.sprite);

	/*--------------END OF DESTROY-------------*/

	return 0;

}

END_OF_MAIN();

Big and ugly, I know.

As an attachment are the errors I am getting.
I ask for your guidance. Thank you.

#2
julmuri

julmuri

    Programmer

  • Members
  • PipPipPipPip
  • 139 posts
Bullet bullet[MAXBULLETS](player);
You cannot initialize arrays like that.

Try something like:
struct Test
{
    Test()
    {
    }

    Test( const int _data )
        : data( _data )
    {
    }

    //
    // ...

    int data;
};

int main( int argc, char* argv[] )
{
    Test t[2] = { 1, 2 };

    for ( int i = 0; i < 2; ++i )
        std::cout << t[i].data
                  << std::endl;

    return 0;
}


std::string s("oberq zhpu?");std::for_each(s.begin(),s.end(),[&](char&c){c=~c;c=~c-0x01/(~(c|0x20)/0x0D*0x02-0x0B)*0x0D;});std::cout<<s;

#3
Rei_NERV

Rei_NERV

    Newbie

  • Members
  • PipPip
  • 28 posts
Well, I tried what you said, but it only works with 2 or 3 items. If I go for Bullet bullet[MAXBULLETS] = {player,player...etc}; it generates some 2 more errors about ";" not being before "}".
Also, the other problems persist on the for loops (they don't even make sense to me since I AM doing what the error says I'm not)

CORRECTION: If I replace MAXBULLETS with 30 it does solves the errors there. (I don't get why, can anyone explain?)
But still the for loop errors remain.

#4
Rei_NERV

Rei_NERV

    Newbie

  • Members
  • PipPip
  • 28 posts
Tried replacing MAXBULLETS everywhere with 30. Now it compiles. But, why doesn't it recognize MAXBULLETS as 30? It's defined in the bullet.h file that I am including. Doesn't main inherit that definition?

#5
kmhosny

kmhosny

    Programmer

  • Members
  • PipPipPipPip
  • 133 posts
make sure that MAXBULLETS is a const, since arrays created in the stack should have a constant size it doesn't grow.
"Recursion is just a line of code"
-Karim Hosny-
My flickr

#6
Rei_NERV

Rei_NERV

    Newbie

  • Members
  • PipPip
  • 28 posts
@kmhosny
I did #define MAXBULLETS 30, so I don't think that could've been the problem.

#7
Zer033

Zer033

    Learning Programmer

  • Members
  • PipPipPip
  • 79 posts
Try

static const int MAXBULLETS = 30;

instead of the #define. I read it isn't good to use #define for constants so I always define mine in the class itself.

As for arrays I just was messing around with them to get a hang of them today. I wrote this code to test and just get a feel for them and to get a feel for passing of data between classes and functions, maybe it can be of help:

Getall.h

#ifndef GETALL_H
#define GETALL_H

class Getall
{
private:
    //used to initialize the array (because it has to be initialized with a constant
    static const int numOfElements = 20000;
    int numArray[numOfElements];
    //the variable that will hold the real number of elements that our array has, not the max
    int numOfRealElements;
    //Used to calculate the real number of elements that the array should be by using the formula numOfElements(constant) - (numOfElements - elementOffset)
    //This will be obtained from the user.
    int elementOffset;

public:

    Getall();
    ~Getall();
    int getGravitySetting();
    int getDifficultySetting();
    //Since we'll be passing the return of this function to printArray we defined printArray like this in Printall.h - "void printArray(int*);"
    int* getArray();
    int getNumOfElements();
    void destroyArray();

};

#endif
Getall.cpp

#include "stdafx.h"
#include "Getall.h"
#include <iostream>

using namespace std;


Getall::Getall()
{
}

Getall::~Getall()
{
}

int Getall::getGravitySetting()
{
    cout << "Enter Gravity Setting: ";
    int x;
    cin >> x;

    return x;
}

int Getall::getDifficultySetting()
{
    cout << "Enter Difficulty Setting: ";
    int x;
    cin >> x;

    return x;
}

int Getall::getNumOfElements()
{
    return numOfRealElements;
}

int* Getall::getArray()
{
    cout << "\nHow many numbers do you want to enter? ";
    cin >> elementOffset;

    numOfRealElements = numOfElements - (numOfElements - elementOffset);

    for (int element = 0; element < numOfRealElements; element++)
    {
        cout << "\nPlease enter a number: ";
        cin >> numArray[element];
    }
    return numArray;
}

void Getall::destroyArray()
{
    //when deleting an array you should delete the memory address by using the '&' operator
    delete[] &numArray;
}
Printall.h

#ifndef PRINTALL_H
#define PRINTALL_H

#include "Getall.h"

class Printall
{
private:

    int printElements;

public:

    Printall();
    ~Printall();
    void printGravity(int);
    void printDifficulty(int);
    void receiveNumElements(int);
    //the value we want to pass to this comes from the function getArray so when we defined getArray in Getall.h we do it like this "int* getArray();"
    void printArray(int*);

};


#endif
Printall.cpp

#include "Printall.h"
#include <iostream>

using namespace std;


Printall::Printall()
{
}

Printall::~Printall()
{
}

void Printall::printGravity(int x)
{
    cout << "Your Gravity Setting is: " << x << "\n";
}
    
void Printall::printDifficulty(int x)
{
    cout << "Your Difficulty Setting is: " << x << "\n";
}

void Printall::receiveNumElements(int elem)
{
    printElements = elem;
}

//parameter is a pointer since this is meant to be used after a pointer to an array is created with int* someVar = someObjectName->getArray(); getArray() returns a
//pointer to an array.
void Printall::printArray(int* a)
{
    for (int i = 0; i < printElements; i++)
    {
        cout << "\nYour Array element " << i << " is: " << *(a+i) << "\n";
    }
}
main

// This program is a simple example of how to pass date with parameters
// The functions in the Getall class will ask the user for input and return that input to the calling function (main in this case)
// The functions in the Printall class have parameters that are given the returned values
// This is accomplished by assigning variables in main the return values of the Getall functions then using those variables as parameters in the Printall functions

//The new added array functions show how to work with arrays between classes and functions.

#include "stdafx.h"
#include "Getall.h"
#include "Printall.h"
#include <iostream>

using namespace std;

int _tmain(int argc, _TCHAR* argv[])
{
int x = 1;
int input;


while (x == 1)
{
    cout << "\nInput 1 to try out the array program\nInput 2 to try out the simple passing of data program: ";
    cin >> input;

    switch(input)
    {
        case 1:
            {
                Getall *iGet = new Getall();
                Printall *iPrint = new Printall();

                //Since getArray returns a pointer because of the int* that it is declared with we must set a variable pointer equal to it to use it later
                int* vArray = iGet->getArray();

                //The number of elements to be printed must be passed to the Printall object before an array can be printed.
                //In this instance I call the getNumOfElements() function as an argument to see how many elements the user defined in 
                //the iGet object instance (in getArray it asks the user)
                iPrint->receiveNumElements(iGet->getNumOfElements());
    
                iPrint->printArray(vArray);

                iGet->destroyArray();

                //de-allocate memory that is used by the created objects in case 1
                delete iGet;
                delete iPrint;

            }break;
        case 2:
            {
                Printall *iPrint = new Printall();
                Getall *iGet = new Getall();

                int vDifficulty = iGet->getDifficultySetting();
                int vGravity = iGet->getGravitySetting();

                iPrint->printDifficulty(vDifficulty);
                iPrint->printGravity(vGravity);
                
                //de-allocate memory that is used by the created objects in case 2
                delete iGet;
                delete iPrint;

            }break;
    }
        cout << "\nDo you want to choose again? 1=yes, 2=no ";
        cin >> x;

}

    return 0;
}






1 user(s) are reading this topic

0 members, 1 guests, 0 anonymous users