如何从另一个类访问数组

How to access an array from another class?

本文关键字:访问 数组 另一个      更新时间:2023-10-16

>我试图从密码游戏类访问我的数组y,我在密码游戏类中公开声明了数组,以便在我的其他类中可以访问它。

这是我过去在 y 什么是全局变量时所拥有的。

for (int j =0; j < 4; j ++ ) {
                bool flag = false;
                if ( x[j] ==  y[j] ) {
                    cout << "O";
                    finish[j] = true;
                    continue;
                }

现在作为类 PasswordGame 中的 y 变量我这样做,我的错误是"成员引用基类型"int"不是结构或联合"。

PasswordGuessingGame u;
     for (int j =0; j < 4; j ++ ) {
                    bool flag = false;
                    if ( x[j] ==  u.y[j] ) {
                        cout << "O";
                        finish[j] = true;
                        continue;
                    }

但是,如果我公开声明,它会起作用,但在循环中无法正常工作。

public: 
int two = u.y[j];

谢谢!

我不知道

你是如何声明你的类定义的。但这里只是为了演示一个简单的例子:

#include <iostream>
class PasswordGuessingGame{
public :
int x[5]={1,2,3,4,5};
};
class anotherClass{
public :
int y[5]={11,22,33,4,6};
};
int main(){
PasswordGuessingGame u;
anotherClass v;
int finish[5];
for (int j =0; j < 4; j ++ ) {
            bool flag = false;
            if ( u.x[j] ==  v.y[j] ) {
                std::cout << "O";
                finish[j] = true;
            }
        }
return 0;
}