更改不同类的数组中的值

Changing values in arrays of a different class

本文关键字:数组 同类      更新时间:2023-10-16

(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这样的变量名可能会导致严重的问题。