在另一个类中使用变量 [英] Use variable in another class
本文介绍了在另一个类中使用变量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
B类在A类中实例化:
Class B is instantiated in class A:
Class A {
int x, y;
B b;
}
我如何才能从类B的成员函数中使用变量x和y?
How can I use variables x and y from member functions of class B?
推荐答案
我认为,如果您获得有关类设计的更多知识,那就更好了. > 因此,我希望您能看一看C ++的书籍,例如Stanley B Lippman的C ++ Primer.
好吧,看你的情况
I think, it better if you get some more knowledge regarding class design.
So i prefer you to have a look with some book in C++ like C++ Primer from Stanley B Lippman.
Well see your case
class B
{
public:
void SetAVal( int X1, int Y1 )
{
LocalX = X1;
LocalY = Y1;
}
private:
int LocalX, LocalY;
};
Class A {
int x, y;
void SetValTOB()
{
b.SetAVal( x, y );
}
B b;
}
您应该购买一本有关C ++的书,并阅读有关面向对象编程的工作方式的章节.您的问题毫无道理.类A没有变量,类A的实例却没有.如果B具有A的实例,则可以访问A中的变量.A在此处具有B的实例,并且可以访问其中的值(如果它们是公共的).您必须将A的实例传递到B的函数中,或直接传递x/y值.否则将无法访问它们.
You should buy a book on C++ and read the chapters on how object oriented programming works. Your question makes no sense. Class A has no variables, instances of class A do. If B has an instance of A, it can access the variables in A. A has an instance of B here, and can access values in it, if they are public. You''d have to pass the instance of A into the function in B, or pass the x/y values in directly. It can''t access them otherwise.
您不能在任何其他类中直接使用A中声明的变量,无论是否嵌套.您将必须传递A的实例,然后使用A的成员函数访问其变量.
-Saurabh
You cannot directly use variables declared in A in any other class, whether nested or not. You will have to pass an instance of A and then use member functions of A to access its variables.
-Saurabh
这篇关于在另一个类中使用变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文