从另一个类调用类方法 [英] calling a class method from another class
问题描述
我想在类A的方法成员中更改类B的变量成员。
示例:
I want to change a variable member of class B, in a method member of class A. Example:
A.h:
class A
{
//several other things
void flagchange();
}
A.cpp:
void A::flagchange()
{
if (human) Bobj.flag=1;
}
我知道我需要一个B类的对象来更改一个可变成员但是B中的对象在A中是不可达的。可以通过指针来实现。
I know that I need an object of class B, to change a variable member of B, but objects of B are not reachable in A. Is it possible by a pointer??
推荐答案
但B中的对象在A中无法访问
but objects of B are not reachable in A
如果类B的对象无法通过类A访问,可以修改它们。一旦你重构你的设计,你应该将它作为参数传递给函数:
If objects of class B are not reachable by class A there's no way you can modify them. Once you refactored your design, you should pass it as an argument to the function:
class A {
//several other things
void flagchange(B& obj) {
if (human)
obj.flag = 1;
}
};
我想要能够从类的方法A的每个对象B
I want to be able to toggle the flag from a method of class A for every object of B
您应该将标志
static
in B
:
class B {
public:
static int flag;
};
int B::flag = 0;
然后,从 A
:
class A {
//several other things
void flagchange() {
if (human)
B::flag = 1;
}
};
这篇关于从另一个类调用类方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!