0

I used to do it in high school but I haven't practised for a couple of years. What I'm trying to do is create an array which will store 100 IDs from 1-100. (This is for a game where each item will be assigned one of these IDs to distinguish each item from one another) This is my code,

#include <iostream>
#include <string>

using namespace std;

class items_class
{
public:
    items_class();
    ~items_class();
    static int item_ID[100];
};

items_class::items_class()
{
    for(int i=0;i<=100;i++)
        {
            item_ID[i] = i;
        }

}

int main()
{
    items_class items();

    for(int x=0;x<=100;x++)
        {
            cout << items.item_ID[x] << endl;
        }
}

but when I try to compile it I get this error:

main.cpp:29:27: error: request for member 'item_ID' in 'items', which is of non-class type 'items_class()' cout << items.item_ID[x] << endl;

Can anyone tell me why this is occurring? It's probably really obvious but I can't figure it out and I have scoured the internet all night! Grr.

Thanks in advance!

2 Answers2

0

Here's what you were missing, you declared your static variable but never defined it!

#include <iostream>
#include <string>

using namespace std;


class items_class
{
public:
    items_class();
    ~items_class();
    static int item_ID[100];
};

int items_class::item_ID[100]; // Need to define the static variable in a compilation unit.
items_class::items_class()
{
    for(int i=0;i<=100;i++)
        {
            items_class::item_ID[i] = i;
        }

}

int main()
{
    items_class items();

    for(int x=0;x<=100;x++)
        {
            cout << items_class::item_ID[x] << endl;
        }
}
Kam
  • 5,878
  • 10
  • 53
  • 97
0

The previous answer assumed that the static variable is what you wanted. Another approach is to remove the static keyword. Then, when declaring items, remove the parens

KC-NH
  • 748
  • 3
  • 6