| |||||||||
![]() |
|
|
«
Previous Thread
|
Next Thread
»
|
Thread Tools | Search this Thread | Display Modes |
|
#1
|
|||
|
|||
|
Help with class constructors?
Alright here is the problem. I am able to pass variables into a class with constructors but am having dificulty in passing arrays. The array already exists inside of the class but i want to give it values when I create a variable of my class. Now I know that i need to use pointers to pass arrays into a function like so...
int add (int *list); main(){ int list[5]={1,2,3,4,5}; cout << add(list); } int add (int *list){ int x; x=list[0]+list[1]+list[2]+list[3]+list[4]; return x; } Now while this works fine if i'd try and do something in a constructor like this... class acsl{ private: int card[5]; int check[5]; int combos[13]; int flush[5]; int two; int three; int four; int straight; short j; public: void reset(); void adjust(); void print(); void input(); acsl(int *card); }; acsl::acsl(int *card) { acsl::card=card; } Where a list of cards is what i want to assign when i create a variable of my class. |
|
#2
|
|||
|
|||
|
to access objects of a class from within a member function, use the this pointer.
Code:
this->card = card; the this pointer is created and destroyed automatically by the compiler, and points to the instance of the class that the member function was called for. FYI, you don't actually need to use the this pointer to access member variables from within member functions, so this code Code:
card=card; would work the same as my first example. Last edited by ubergeek : March 26th, 2005 at 01:37 PM. Reason: added semicolons (d'oh!) |
|
#3
|
|||
|
|||
|
Code:
acsl::acsl(int *card)
{
acsl::card=card;
}
Wont work. You can't simply assign arrays you must copy them. Try this: Code:
acsl::acsl(int *inCard)
{
for (int i = 0; i <= 4; i++) {
card[i] = inCard[i]
}
}
Also, get away from using hard coded values for your array sizes - use consts instaed. That way if you ever want to change the size of the array, you just change the const and you don't have to go through your code looking for all the places you hard coded the array size. Makes software maintenace a whole lot easier. |
![]() |
| Viewing: Dev Articles Community Forums > Programming > C/C++ Help > Help with class constructors? |
| Thread Tools | Search this Thread |
| Display Modes | Rate This Thread |
|
|
|
|