0

I have a program, call it X, that uses two classes: call them Y and Z. X uses Y which uses Z. Y contains an array of Z's.
How do I construct an array of Z's and still allow me to set Z's variables.
For example I know how to declare an array of classes:

Z arrayOfZ[NUM]

and I know how to set values:

Z newZ(5)

but how do I do both?

Thanks

3
Contributors
3
Replies
4
Views
7 Years
Discussion Span
Last Post by mtusk
0

Not sure if I udnerstand the question, but I think you mean something along the lines of setting a value of one of the Z variables in the array?

struct Z{

    int a;
    int b;

    Z() : a(0), b(0) {}

    void setA(int x){ a = x; };
    void setB(int y){ b = y; };
};

int main(){

   Z arrayOfZ[10];
   Z[0].setA(5);
   
   // ... etc
   

   return 0;
}

If not and you want to construct an array of Z's with a specified constructor to apply for each Z, I don't know but I think its possible.

0
#include<iostream>
using std::cout;

struct Test
{
	int i;
	Test(int j) { i = j; }
	void show() { cout << i << "\n"; }
};
int main() 
{
	Test test[3] = { Test(1), Test(2), Test(3) };
	test[0].show();
	test[1].show();
	test[2].show();
  return 0;
}

//prints 1 2 3

Of course you know that struct and classes are almost similar except
for their default behavior, so you can do this with classes as well.

0
Test test[3] = { Test(1), Test(2), Test(3) };

That's exactly what I was looking for! Thanks!

This topic has been dead for over six months. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.