从分隔符.cpp指向数组的指针

pointer to array from serperate .cpp

本文关键字:数组 指针 分隔符 cpp      更新时间:2023-10-16

试图从一个单独的。cpp指向一个数组,但从我的数组。

main.cpp

int main()
{
    storage exp;
    cout << exp.pointer[0];
    _getch();
    return 0;
}

storage.h

class storage
{
    public:
    storage();
    int* pointer = experience;
    int storage::experience[10];
    ~storage();
};

storage.cpp

storage::storage()
{
}
int experience[10] = { 100, 200, 400, 600, 1000, 2500, 3000, 4000, 5000, 10000;
storage::~storage()
{
}

这是rpg游戏。我需要返回数组值,但我不能这样做,我不能从头创建数组因为它是手工制作的值。它必须去某个地方。我不想把它放在main(之前在单独的代码中这样做),因为我试图学习如何用指针做到这一点,但我做了一些严重的错误。

我不认为存储指针并让每个对象包含自己的指针是最好的方法。如果存储类的所有对象共享experience[10]数组的相同值,那么您应该在storage.h中的storage类的声明中将其声明为static int,而不是int。不要指定它在类storage中;您在类声明中声明变量,因此不需要这样做。

class storage
{
    //other variables
    static int experience[10];
};

然后在storage.cpp中输入:

int storage::experience[10] = { 100, 200, 400, 600, 1000, 2500, 3000, 4000, 5000, 10000 };

(不要忘记分号前的结束大括号!)

存储类中的所有对象"共享"整型数组;

该成员只有一个实例,任何对象都可以访问它。

你说:

试图从一个单独的。cpp指向一个数组,但从我的数组得到NULL值

首先,这行

int storage::experience[10];

是无效的c++代码。编译器应该将其报告为错误。在storage.h中您可能想要的是:

extern int experience[10];
class storage
{
    public:
    storage();
    int* pointer = experience;
    ~storage();
};