简体   繁体   English

如何从C ++中的类在主函数中调用数组?

[英]How to call an array in the main function from a class in C++?

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. 我想做的是创建一个数组,该数组将存储1-100个ID。 (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, (这是一种游戏,其中将为每个项目分配一个ID以区分每个项目)这是我的代码,

#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; main.cpp:29:27:错误:在'items'中请求成员'item_ID',该成员是非类类型'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. r

Thanks in advance! 提前致谢!

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;
        }
}

The previous answer assumed that the static variable is what you wanted. 先前的答案假定您想要的是静态变量。 Another approach is to remove the static keyword. 另一种方法是删除static关键字。 Then, when declaring items, remove the parens 然后,在声明项目时,删除括号

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM