如何访问与其他类不同的类中的变量
How to access variables in different class from other class
x不能是静态的
我想要
class A{
static std::vector<C> vec_ca;
public:
int x = 6;
`};
class B{
std::vector<C> vec_cb;
public:
int x = 7;
};
class C
{
void foo(){
int k = x;
}
};
, k将根据它的类而定:如果k in vec_ca k = 6;如果k in vec_cb k = 7。有可能做到吗?
有两种方法。你可以像这样使用getter和setter方法:
class B{
std::vector<C> vec_cb;
public:
int get_x(){return x;}
private:
int x = 7;
};
,从另一个类调用get_x
。另一种实现方法是使用好友类。你可以输入:
class B{
std::vector<C> vec_cb;
friend class A;
private:
int x = 7;
};
相关文章:
- 有没有什么方法可以使用一个函数中定义的常量变量,也可以由c++中同一程序中的其他函数使用
- 类与私有变量的其他类之间的线程安全性
- C++变量名(可以将 main 声明为变量,但对于其他函数名称则不然)
- 是否可以使用其他变量为变量分配值,而无需在 C++ 中更改其值?
- 如何从其他结构访问受保护的结构变量
- 在命名空间中声明变量,在 main 中定义它,使其对所有其他文件可见
- 为什么当我没有变量或其他任何命名的东西时"no match for 'operator==' "错误?
- 访问从 CPP 文件到其他头文件的静态变量
- 将其他函数中的变量用于主函数C++
- 如何将几个变量复制到其他变量
- 继承构造函数和其他变量的解决方法
- C++ 在方程中使用变量;错误:表达式必须具有整数或无作用域枚举类型及其他
- 变量 z 无法从其他函数访问变量 x
- 没有模板变量的模板化类型和其他使用此类的模板化类型
- 从其他类声明类类型变量会给出 C2143 错误(在"*"之前缺少";")
- 我的 c 字符串复制函数正在损坏其他变量的堆栈
- 如何在需要提及需要循环声明的其他类的类中初始化变量?
- 使用全局变量初始化不同编译单元中的其他全局变量
- C++setenv 解析其他变量
- 仅为特定条件重置变量的值,并为其他所有条件重置固定值