Declaring Array

Hi,

what I am trying to do is this:

name.h contains a class "support"
1
2
3
4
5
6
7
8
class support{
 private
  int nr=8;
  int array[nr];
 public
  int another[nr]
...
}

This nr should be usable in name.c++ in routines like support::something.

The problem is that I cannot initialise nr like this. Is there a way to achieve the same goal?
Last edited on
1
2
3
4
5
6
7
8
9
10
11
class support
{
private:
    enum { nr = 8 };

    int array[nr];

public:
    int another[nr]
    //...
};
There are two errors in these lines:
1
2
  int nr=8; // Current C++ doesn't support this syntax for in-class initialization
  int array[nr]; // automatic array must have a constant as size -nr is a variable- 

If you need 'nr' to always be the same, you can declare it as a static const member, in that case your code will work:
1
2
3
4
5
6
7
8
class support{
   private:
      static const int nr=8; // OK, static const integral type can be initialized like this
      int array[nr]; // OK, nr is constant
   public:
      int another[nr]; // OK
      //...
};


If you want 'nr' to have diffenent values for different instances you can use a template:
1
2
3
4
5
6
7
8
template < int nr > // I would suggest you an unsigned int as it represents a size
  class support{
     private:
        int array[nr]; // OK, nr is constant
     public:
        int another[nr]; // OK
        //...
};

Topic archived. No new replies allowed.