有什么方法可以在其他类中传递类的变量吗

Is there any way to pass a variable of class in other class?

本文关键字:变量 其他 方法 什么      更新时间:2023-10-16

我想要两个类。我在类Class1中有一个静态变量,我想把它得到的值传递给类Class2

例如:

//Class1.h
{
    static int x;
    int Method1();
}
//Class1.cpp
{
    int Class1::x=0;
    int Class1::Method1(){
    x=2;
    }
}

现在是Class2

//Class2.cpp
{
   Class1 cls;
   cout<<cls.x<<endl;//it shows 0 value
}

我假设x是公共的:

#include "class1.h"
int xVal = Class1::x;

您需要将要访问变量的另一个类声明为"friend"

class Class1 {
    friend class Class2;
    // ...
}

现在,您可以在Class2中访问Class1中的所有变量。