从分隔符.cpp指向数组的指针
pointer to array from serperate .cpp
试图从一个单独的。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();
};
相关文章:
- 添加到数组指针
- C++语法差异:二维和一维数组(指针算术)
- 数组指针表示法C++(移动数组时)
- 复制后删除原始数组指针将前 3 个字节设置为 0
- C++访问指向结构的指针中的类数组指针
- C++编译时使用 constexpr 字符数组指针分配静态数组?
- std::flush可以用于将对象指针转换为其封闭数组指针吗
- 创建<int>对整数数组指针的矢量引用 (C++)
- 将 2D 数组指针传递给 C++ 中的函数
- 创建指针是否超过非数组指针的末尾,而不是从 C++17 中的一元运算符和未定义的行为派生?
- 队列数组指针 (C++)
- C++数组指针上的删除操作
- 对于循环不循环和检测字符数组 [指针和字符数组]
- 如何初始化数组指针对象
- 如何正确传递 2D 数组指针作为参数
- 从数组指针中获取怪异的数字
- 初始化std :: unique_ptr作为原始数组指针的初始化
- 将结构数组指针从C#传递到C
- STD :: Sort将数组指针设置为NULL
- C++数组指针错误无法将“int*”转换为“int**”