如何从其他类访问不同的类变量
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在vec_ca K = 6;如果k在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;
};
为什么要返回类的值应该引用? –
您的程序为错误。找出错误。大声笑 –
@ vinothcse2000什么?对不起,我刚刚从午餐回来,哦对不起...我的错,我以为他真的想改变变量..更改 – amanuel2
你可以使用getter和setter方法。 – Charles
为什么你不希望x是静态的? –
如果你不希望它是静态的,那么你必须为各个类创建对象 –