更改不同类的数组中的值
Changing values in arrays of a different class
(c++问题(我有两个类A和B,以及主类(int main(。我在 A 类中有一个数组。在主类中,我想对类 A 中的数组进行更改。当类 B 从类 A 读取数组时,它应该读取更改的值。但是,我对 A 类到 int main 中所做的数组所做的更改仅对 int main 中的所有内容生效,而不是 B 类。换句话说,我无法永久更改类 A 中的值。 我创建了一个虚拟程序(c ++(来展示我的问题。如果我为 x(第一个 cin(输入 3,为 y(第二个 cin(输入 9,则输出为
00090
0
什么时候应该
00090
9
#include <math.h>
#include <string>
#include <stdio.h>
#include <iomanip>
#include <iostream>
using namespace std;
class A {
public:
int array[5] = { 0,0,0,0,0 };
int getNum(int index)
{
return array[index];
}
void changeNum(int index, int change)
{
array[index] = change;
}
};
class B {
public:
A obj1;
int getNum(int index)
{
return obj1.getNum(index);
}
};
int main()
{
A obj2;
B obj3;
int x,y;
cout << "Original Array: " << endl;
for (int i = 0; i < 5; ++i)
cout << obj2.getNum(i);
cout << endl << endl << "Enter index number:" << endl;
cin >> x;
cout << "Enter new number" << endl;
cin >> y;
obj2.changeNum(x, y);
for (int i = 0; i < 5; ++i)
cout << obj2.getNum(i);
cout << endl << obj3.getNum(x) << endl;
system("pause");
return 0;
}
如果您希望对A
中的array
的更改全局可见,则可以array
像这样创建一个static
变量:
class A {
public:
static int array[5];
// ...
};
int A::array[5] = { 0,0,0,0,0 };
从 c++17 开始,您还可以在类中定义array
:
class A {
public:
inline static int array[5] = { 0,0,0,0,0 };
// ...
}
这是一个演示。
另外,避免做using namespace std;
,例如已经有一个std::array
,所以像array
这样的变量名可能会导致严重的问题。
相关文章:
- Mongodb c++驱动程序:如何查询元素的数组
- 将数组的地址分配给变量并删除
- 从C++本机插件更新Vector3数组
- lambda参数转换为constexpr技巧,然后获取带链接的数组
- 将数组作为参数传递给函数安全吗?作为第三方职能部门,可以探索他们想要的之外的其他元素
- 数组索引的值没有增加
- 将对象数组的引用传递给函数
- 为char数组调整zlib-zpipe
- 更改不同类的数组中的值
- 不同类对象的数组
- 函数指针数组,其中包含不同类的类函数
- 如何在来自不同类的字符串或字符数组中显示特定字符
- 未定义的引用:试图初始化来自不同类的对象的指针数组
- C++11 在不同类之间共享固定大小的数组
- 当使用来自不同类的字符数组是安全的时
- inheritance:如何用相同的函数生成一个不同类的数组,这些类在C++中做不同的事情
- 不同类的数组
- 指向从 1 个基类继承的不同类对象的指针数组
- 指向不同类的函数的函数指针数组
- 具有相同类层次结构的C++数组