开发者

static member in c++

I was experimenting with static keyword in c++. The following class has a static variable called size which is initialized as 10.

class staticTest
{
    public:
            static int size;
            int x,y;

            staticTest()
            {
                x=0;
               开发者_如何学编程 y=0;
            }
            void display()
            {
                printf("%d %d\n",x,y);
            }
};   
int staticTest::size=10;

Now i have another class which uses this static variable. Here is the other class

class my
{
    public:
            int a[staticTest::size];

            my()
            {
                for(int i=0;i<staticTest::size;i++)
                {
                    a[i]=i;
                }
            }

            void display()
            {
                for(int i=0;i<staticTest::size;i++)
                {
                    printf("%d\n",a[i]);
                }
            }
};   

Now i have main function like this

main()
{
    my ni;
    ni.display();
}

I am unable to compile this program. Error is that array bound is not an integer constant. Why is this so?


Only compile-time constants can be used as array sizes.

Declare your integer as static const int.

Also, the (default) value needs to go in the declaration, not the definition:

// in header
class Foo {
public:
  static const int n = 10;
};

// in implementation
const int Foo::n;

Based on your comment, consider this: At the moment, you are effectively using a global variable to communicate some dynamic quantity. This should ring alarm bells:

int size; // global

void some_UI_function(); // modifies `size`?!

void some_computation()
{
  int data[size]; // pseudo-code
  // ...
}

This is terrible design, for a whole range of reasons. Instead, you should make the relevant size part of the class:

class my
{
  std::vector<int> m_data;
public:
  my(std::size_t n) : m_data(n) { }
  // ...
};

Now you can communicate the desired size locally:

int main()
{
  size_t n = get_data_from_user();
  my x(n);
  x.compute(); // etc.
}


Arrays are static, which means that their size is being set at compile time. Therefore, you need to use integer constants to declare an array.


That is because your static variable can change value during the duration of your program, if you add the const qualifier, like so static const int size = 10; it should work as expected.


The static keyword when used inside a class definition does not mean that the variable won't change, but that the entire class has one copy of the variable (instead of each instance having a copy). That, coupled with the fact that you can only use values known at compile time as an array size, is what's giving you your error.

You can fix the compile error by changing size to const and giving it a value:

static const int size = 5; // 5 for instance

However, weird things can start happening when you try to take the address of that variable since it doesn't really exist anywhere1, so instead of that, the preferred method is to have this in your definition:

static const int size;

And then in one implementation (.cpp) file, have the definition:

static const int staticTest::size = 5;

1 It may not look like it, but this variable only has a definition and no declaration. In some compilers it may work, where they will just substitute that variable in places it is used with the number it represents, but it's undefined behaviour and will fail to link in others, so don't count on it (as pointed out by James Kanze in the comments).


The static keyword specifies that the variable has static duration (it is allocated when the program begins and deallocated when the program ends).

Only compile-time constants can be used as array sizes. declare your size as static constant, also note that default value must go in declaration, not in definatio


for dynamic deciding the size of array as per ur comment use----

When the desired size of an array is known, allocate memory for it with the new operator and save the address of that memory in the pointer. Remember: Pointers may be subscripted just as arrays are. The example below reads in a number and allocates that size array.

int* a = NULL;   // Pointer to int, initialize to nothing.

int n;           // Size needed for array
cin >> n;        // Read in the size
a = new int[n];  // Allocate n ints and save ptr in a.
for (int i=0; i<n; i++) {
    a[i] = 0;    // Initialize all elements to zero.
}
. . .  // Use a as a normal array
delete [] a;  // When done, free memory pointed to by a.
a = NULL;     // Clear a to prevent using invalid memory reference.


The static keyword specifies that the variable has static duration (it is allocated when the program begins and deallocated when the program ends).

The elements field within brackets [] which represents the number of elements the array is going to hold, must be a constant value, since arrays are blocks of non-dynamic memory whose size must be determined before execution. In order to create arrays with a variable length dynamic memory is needed.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜