【问题标题】:Changing values in arrays of a different class更改不同类的数组中的值
【发布时间】: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++


【解决方案1】:

如果您希望对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 };
  // ...
}

这是demo

另外,避免使用using namespace std;。例如已经有一个std::array,所以像array 这样的变量名可能会导致严重的问题。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-03-10
    相关资源
    最近更新 更多