Archived

This topic is now archived and is closed to further replies.

StormUK

How would i pass an array of a class to a function?

Recommended Posts

StormUK    122
Title says it all - here is what i have tried so far
  
#include <iostream.h>
#include <windows.h>
#define null 0

class mob
{
public:
	mob()
	{
		posx=0;
		posy=0;
		type=0;
		health=0;
		mana=0;
		ac=0;
		dc=0;
		id=0;
		lastattack=0;
		lastcast=0;
		spellid=0;
		buffid=0;
		castdelay=0;
		attackdelay=0;
	}
	void move(){

	}
	void attack(){
		int now=GetTickCount();
		if(now>=(lastattack+attackdelay))
		{
			cout<<"Attack!"<<endl;
			lastattack=GetTickCount();
		}
	}
	void spell(){
		int now=GetTickCount();
		if(now>=(lastcast+castdelay))
		{
			cout<<"Spell!"<<endl;
			lastattack=GetTickCount();
		}

	}
	void buff(){
		int now=GetTickCount();
		if(now>=(lastcast+castdelay))
		{
			cout<<"Buff!"<<endl;
			lastattack=GetTickCount();
		}
	}

	int posx, posy;
	int type, health, mana, ac, dc, id;
	int spellid, buffid;
	int lastattack, lastcast, castdelay, attackdelay;
};
class spell
{
public:
	spell();
	void effects(){

	}
	spell *next;
private:
	int id;
	int targetid;
	char name[25];
	int duration;
	int tick;
	int range;
	int AC;
	int DC;
	int mana;
	int health;
	int speed;
	int damage;
	int costMP;
	int costHP;
	int level;
	int castTime;
	int radius;
	int cooldown;
	char effect[256];
	char icon[256];
};
class buff
{
public:
	buff();
	void effects(){

	}
	buff *next;
private:
	int id;
	int targetid;
	char name[25];
	int duration;
	int tick;
	int range;
	int AC;
	int DC;
	int mana;
	int health;
	int speed;
	int damage;
	int costMP;
	int costHP;
	int level;
	int castTime;
	int radius;
	int cooldown;
	char effect[256];
	char icon[256];
};

mob mobs(mob monster[]);

int main()
{
	bool done=false;
	int i=0;

	mob monster[10];
	
	//Load Map

	//Load Spells

	//Load Buffs

	//Load Mobs

	//Load Items

	//Load Player


	while(!done)
	{
		monster=mobs(monster, 10);
		
		//Spells

		//Buffs

	}


	return 0;
}

mob mobs(mob monster[], int nummon)
{
	int i=0;
	for(i=0;i<nummon;i++)
	{
		monster[i].attack();
		monster[i].buff();
		monster[i].spell();
	}
				
	return monster;

}
  
Thanks, Chris.

Share this post


Link to post
Share on other sites
GoofProg    127
class A {
friend void B(A&,int);
private:
int var;
}

..
..

void B(A& integer, int number)
{
integer.var=number; //this works now
}


Something like that





Share this post


Link to post
Share on other sites
StormUK    122
gah, i dont 'think' you undersand what i want..

ill try again

Say i had an array and i had a function and i wanted the function to take the array, manipulate the data, then pass it back to the main loop, how would i do this?

could i use the same method if i had an array of a class?

eg;

      
class a{
int blah
void somthing() {
blah++;
}
};

a somestuff(a myclass);

int main(){
a myclass[10];

myclass=somestuff(myclass);
for(int i=0;i<10;i++){
cout<<myclass[i].blah<<endl;
}
return 0;
}

a somestuff(a myclass){
for(int i=0;i<10;i++){
myclass[i].somthing
}
return myclass;
}


[edited by - StormUK on March 7, 2003 10:33:32 AM]

Share this post


Link to post
Share on other sites
GoofProg    127
so the array is declared from the main function and
you want to pass the WHOLE array to an outside function and have that data pass back to main??

do something like this...

void ManipData(myclass array[])
{
..the magic happens here
...

}

int main()
{
myclass myarray[10];
ManipData(myarray);
}


myarray holds the address of the myarray[0]

sorry if i still don''t understand your question

Share this post


Link to post
Share on other sites
Tyson    122
You can just return the array refernce from the paramter. Since you are effectively passing a pointer to the first item in your array, any modification done to the array contents by the function will still be present when the function exits. Passing the array back is needless really.

if you really still want the array back, check this little sample out:


  
#include <string>
#include <iostream>

using namespace std;

class myclass {
public:
int x;
};


myclass* func(myclass p[]) {

//magic code of goodness here


return p;
};


void main() {


myclass array[10];
myclass* arrayptr;

arrayptr = func(array);


for(int i=0;i<10;i++) {
array[i].x = i;
}


cout << arrayptr[1].x << endl;

getchar();

}


Unless I missed the boat one what you are trying to do If so I am sorry.



============================
A guy, some jolt, and a whole lot of code

[edited by - Tyson on March 7, 2003 1:47:06 PM]

Share this post


Link to post
Share on other sites
NeonGE    140
The array is a pointer, when you change the data in another function, then the real original data is changed, you dont need to return it to the main loop

If God with me, Who against me?

Share this post


Link to post
Share on other sites
SabreMan    504
quote:
Original post by StormUK
Title says it all - here is what i have tried so far

Unfortunately, the responses you''ve received are below average even for the low standards of the Gamedev For Beginner''s forum! Here''s some comments that you didn''t ask for...


  • Prefer the header "iostream" over "iostream.h"

  • Don''t use character arrays for storing strings. Use std::string instead. If your learning text doesn''t mention std::string, then throw it away and get a decent one.

  • Look up "initialiser lists"



To answer your immediate question, don''t use arrays at all. Arrays are a really dumb idea that''s been retained in C++ via C since the early seventies. A much better modern version of arrays is std::vector. You can read about std::vector here. Using vectors will make it very easy for you to pass arrays of data around.

Share this post


Link to post
Share on other sites
tok_junior    229
But then again, learning the language before starting
to learn the assorted intricacies of STL is strongly
recommended...

--
MFC is sorta like the swedish police... It''''s full of crap, and nothing can communicate with anything else.

Share this post


Link to post
Share on other sites
SabreMan    504
quote:
Original post by tok_junior
But then again, learning the language before starting
to learn the assorted intricacies of STL is strongly
recommended...

By who?

Share this post


Link to post
Share on other sites
tok_junior    229
By anyone who agrees that you should learn to crawl before you try to run.

--
MFC is sorta like the swedish police... It''''s full of crap, and nothing can communicate with anything else.

Share this post


Link to post
Share on other sites
SabreMan    504
quote:
Original post by tok_junior
By anyone who agrees that you should learn to crawl before you try to run.

Really? Well, I agree with that, but I don''t agree that you shouldn''t learn appropriate Standard Library features early on. Your appeal to popularity seems to have broken.

Share this post


Link to post
Share on other sites
tok_junior    229
STL are templates, which aren''t exactly considered c++ basics. Plus, they''re not applicable in all situations.
He''d be better off learning the language, and then using the bonuses.

--
MFC is sorta like the swedish police... It''''s full of crap, and nothing can communicate with anything else.

Share this post


Link to post
Share on other sites
AikonIV    122
I''m with tok_junior on this one. I''ve been programming c++ for over 2 years. Only within the last couple months have I done any STL other than strings, which I started using about a year ago. Part of the reason is probably because the book I used didn''t have anything about STL. Nonetheless, I know that I would not have been able to use STL properly when I was still learning.

Share this post


Link to post
Share on other sites
SabreMan    504
quote:
Original post by tok_junior
STL are templates, which aren't exactly considered c++ basics.

You don't have to know how to develop templates to be a consumer of templated code. For example, to use a vector of ints, you write:

std::vector<int> v;

After which, you do not need to know anything about templates. This is hardly any more difficult to learn than:

int ar[MAGIC_CONSTANT];

And a vector has tangible benefits over an array, particularly for newbies. For example, you can pass vectors around in a non-braindamaged manner.
quote:

Plus, they're not applicable in all situations.

Who said they were? No one feature is applicable in all situations, so your comment amounts to nothing.
quote:

He'd be better off learning the language, and then using the bonuses.

Who says the C++ Standard Library is some sort of "bonus"? What nonsense is that? Your claim is along the lines of saying a beginner has to learn to write programs without being allowed to #include any standard headers, before they are then allowed to go on and use the standard library as it was intended. How do you support such a nonsensical position?

quote:
Original post by AikonIV
I'm with tok_junior on this one.

You and tok_junior have your work cut out.
quote:

I've been programming c++ for over 2 years. Only within the last couple months have I done any STL other than strings, which I started using about a year ago. Part of the reason is probably because the book I used didn't have anything about STL.
I'm not talking specifically about the STL, I'm talking about the C++ Standard Library of which std::vector and std::string are a part. Having a deficient book is a reason to throw away the book, not to persevere with bad programming practices.
[quote]
Nonetheless, I know that I would not have been able to use STL properly when I was still learning.

I doubt that you had the ability to use *any* feature properly when you were first learning. That's no argument. The point of learning is that you find out how to use things correctly. Learning to use std::vector is no more difficult than learning to use arrays. In fact, I'm prepared to argue std::vector is easier to use, since it behaves how arrays *should* behave, and how newbies assume they behave, whereas arrays are based on 30+ year old idiocy based on vague efficiency concerns. There's utterly no reason to burden newcomers with troublesome, painstaking learning processes just because it's how you did it. There's no arcane rite of passage to learning C++, where you must take a long trek through all the idiotic features before arriving at the sensible stuff.

[edited by - SabreMan on March 8, 2003 11:43:30 AM]

Share this post


Link to post
Share on other sites
RhoneRanger    100
the std::vector is very easy to learn! They "act" like arrays in how you access the data.

For example, to have an array of vertices, in your cpp file you would have (if you define your custom vertex type as Vertex)


  
std::vector<Vertex> Vertices;



Then to allocate the memory for them you would do something like this.

  
for(int i=0;i<NumberVertices;i++)
{
Vertex V;
Vertices.push_back(V);
}

Now you can use Vertices the same way as if you allocated them in an array like Vertex Vertices[MAX_VERTICES];

Vertices[0].color; //etc

Hope this helped!

PS, All you have to do is #include <vector> at the top of your header file. I dont see anything about STL here, so oh well.



[edited by - RhoneRanger on March 8, 2003 3:26:13 PM]

Share this post


Link to post
Share on other sites
tok_junior    229
All i''m saying is that he should learn the pros and cons of (for example std::vector) and the "old" way of doing it. A regular array is for example a lot faster than std::vector, it''s WAY easier to debug, and a lot less complicated to profile.
If you want to learn a language, you''re better off learning it, instead of just learning enough to achieve what you want in an easy way that you don''t understand. Your way of thinking is why games of today won''t run anywhere near to smoothly on a system without tons of ticks and a dx8+ gfxcard. If people were actually interested in learning, and took the extra day o two, a lot of the software of today would be of a lot higher quality.
One example, take the standard A* pathfinding algorithm, which in 99% of the cases are implemented using linked lists. Large linked lists leads to memory fragmentation, and could possible eat HUGE amounts of memory. Whereas my implementation uses a matrix, so it always stays at about 100k, and stays in a continous memoryblock. STL aren''t the answer to everything. Sure, the templates are wonderful for a lot of things, but to actually make the computer perform it''s best, you need to know when to use them, and when not to. And without learning the basics first, you won''t be able to.
Oh, and a nice reference to STL: http://www.sgi.com/tech/stl


--
MFC is sorta like the swedish police... It''''s full of crap, and nothing can communicate with anything else.

Share this post


Link to post
Share on other sites
RhoneRanger    100
quote:
Original post by tok_junior
All i'm saying is that he should learn the pros and cons of (for example std::vector) and the "old" way of doing it. A regular array is for example a lot faster than std::vector, it's WAY easier to debug, and a lot less complicated to profile.



how so?
It is faster to initialize an array(i line of code vs a few), but when it comes down to actual performance, how is reading from an array faster?

How is it easier to debug? You see a problem with Vertices[5], you fix it! profile? ummm ok

Please tell me or show me how anything you just said is true. I am not picking please understand, I just want to know.

EDIT: If you manage your vector, and only push_back the memory needed, how can that cause huge memory loss?

[edited by - RhoneRanger on March 8, 2003 3:47:19 PM]

Share this post


Link to post
Share on other sites
tok_junior    229
Im not saying it always leads to memoryloss, but it leads to memory fragmentation (which in some cases can be worse
The problem im talking about with debugging, is when you''re tracing through the code, you will end up in the stl-code a number of times before you manage to end up in your own code.
std::vector doesn''t (afaik) store the elements sequentially in memory, it requires a lot of jumping around, the same way a linked list does, which is why it''s faster to read/write a regular array. The huge amounts of memory, and the slowdown i was referring to, comes when you''re adding elements to a vector or linked list, it allocates new memory which isn''t very fast.
Like i said, STL is usually a gift from god, but not always, to be able to tell when to use it and when not to, you have to know how your different alternatives work.

--
MFC is sorta like the swedish police... It''''s full of crap, and nothing can communicate with anything else.

Share this post


Link to post
Share on other sites