2016-10-22 122 views
1

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。可以完成吗?

+0

你可以使用getter和setter方法。 – Charles

+0

为什么你不希望x是静态的? –

+0

如果你不希望它是静态的,那么你必须为各个类创建对象 –

回答

3

有两种方法。您可以使用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; 
}; 
+0

为什么要返回类的值应该引用? –

+0

您的程序为错误。找出错误。大声笑 –

+0

@ vinothcse2000什么?对不起,我刚刚从午餐回来,哦对不起...我的错,我以为他真的想改变变量..更改 – amanuel2