Can I have an array in a class?

Can I have an array in a class? If so, what would this look like? I am not very good with classes so any explinations as to why certain things are done would be great.
I can provide an example if you need.
Yes, arrays are usually put in a class as data members, and so generally all containers can be also used in classes e.g
1
2
3
4
5
6
7
8
9
class aClass
{
      aClass();//constructor
      ~aClass();//destructor

private:
     string aStringMember;
     vector<int> aVectorMember;//etc.
};


I can provide an example if you need.

Perhaps you should...
Last edited on
The simplest example I can think of is in the site's tutorial on classes: http://www.cplusplus.com/doc/tutorial/classes/
it has this as an example:
1
2
3
4
5
class CRectangle {
    int x, y;
  public:
    void set_values (int,int);
  } rect;

What would this look like if I wanted to replace int x,y; with int x[2], with the former x as x[0] and the former y as x[1]?
I know that you would replace int x,y; with int x[2]. But what about the set_values, what would it look like?
Also, on line 12 of the site's example is:
1
2
3
void CRectangle::set_values (int a, int b) {
  x = a;
  y = b;

How would it be written if you used int x[2] instead of int x, y;
Last edited on
1
2
3
4
5
6
7
8
9
10
11
class CRectangle {
    int x[2];
  public:
    void set_values (int,int);
    int area () {return (x[0]*x[1]);}
};

void CRectangle::set_values (int a, int b) {
  x[0] = a;
  x[1] = b;
}

in this case it's just as simple as this code. Remember an array is simply an indexed variable i.e
1
2
3
4
5
6
    int a, b, c, x[3];
//put values into a,b,c
//later gives those values to x[0],x[1],x[2]
   x[0] = a;
   x[1] = b;
   x[2] = c;
Thanks a ton! That helps a lot.
Another question, is there any reason why the void CRectangle::set_values (int a, int b){ bit couldn't also contain an array? So instead of (int a, int b), have it contain an array instead? Thanks.
It could if you like, though you'll have no way of knowing the array's size other than passing a parameter because of how array's are passed in C/C++.
Topic archived. No new replies allowed.