【发布时间】:2020-06-08 22:11:44
【问题描述】:
(c++问题)我有两个类A和B,以及主类(int main)。我在 A 类中有一个数组。在主类中,我想对 A 类中的数组进行更改。当 B 类从 A 类中读取数组时,它应该读取更改后的值。但是,我通过 int main 在 A 类中对数组所做的更改仅对 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 类的两个实例,即直接是变量
obj2,也间接是obj3.obj1。 -
@Aziuth 不是一些,很多。我正在通过反复试验学习课程,而不仅仅是阅读教科书或观看教程。
标签: c++