有什么方法可以在其他类中传递类的变量吗
Is there any way to pass a variable of class in other class?
我想要两个类。我在类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
中的所有变量。
相关文章:
- 有没有什么方法可以使用一个函数中定义的常量变量,也可以由c++中同一程序中的其他函数使用
- 类与私有变量的其他类之间的线程安全性
- C++变量名(可以将 main 声明为变量,但对于其他函数名称则不然)
- 是否可以使用其他变量为变量分配值,而无需在 C++ 中更改其值?
- 如何从其他结构访问受保护的结构变量
- 在命名空间中声明变量,在 main 中定义它,使其对所有其他文件可见
- 为什么当我没有变量或其他任何命名的东西时"no match for 'operator==' "错误?
- 访问从 CPP 文件到其他头文件的静态变量
- 将其他函数中的变量用于主函数C++
- 如何将几个变量复制到其他变量
- 继承构造函数和其他变量的解决方法
- C++ 在方程中使用变量;错误:表达式必须具有整数或无作用域枚举类型及其他
- 变量 z 无法从其他函数访问变量 x
- 没有模板变量的模板化类型和其他使用此类的模板化类型
- 从其他类声明类类型变量会给出 C2143 错误(在"*"之前缺少";")
- 我的 c 字符串复制函数正在损坏其他变量的堆栈
- 如何在需要提及需要循环声明的其他类的类中初始化变量?
- 使用全局变量初始化不同编译单元中的其他全局变量
- C++setenv 解析其他变量
- 仅为特定条件重置变量的值,并为其他所有条件重置固定值