修改类中调用另一个类函数的变量
Modifying a variable in class that calls function of another class
我有一个问题,我几乎可以肯定我可以通过重组代码来找到解决方案,我必须消除这个问题,但我想知道是否有办法达到与我现在相同的结果。
假设我们有类 A:
class A
{
public:
int thing;
void dostuff();
std::list<B> mList;
}
void A::doStuff()
{
for(auto x : mList)
x.doMoreStuff();
}
然后是B类。
class B
{
void doMoreStuff();
}
是否有可能以任何方式使 B 的 doMoreStuff 更改类 A 的"int thing"变量,而无需将类 A 的实例传递给 B 或类似的复杂方法?
如果您只想更改某个实例的值,则必须引用。
你可以做的是使用 B 中方法的返回值
class A
{
int thing;
B b;
void dostuff() {
thing += b.doMoreStuff();
};
}
class B
{
int doMoreStuff() {
return 1;
};
}
或者,您可以int thing
或void doMoreStuff()
static
,以便可以从类内存而不是实例内存访问它,如下所示:
class A
{
static int thing;
void dostuff() {
B.DoMoreStuff();
};
}
class B
{
static void doMoreStuff() {
A.thing += 2;
};
}
是的,你可以简单地传递 A 的 int 事物的地址,例如:
B.doMoreThing(&myInt);
doMoreThing的定义是:doMoreThing(int * myInt)
,当修改函数内部int的值时,您应该这样做*myInt+=5
*
对于访问变量很重要。
如果没有引用或指向事物的指针,您将无法写入事物。也就是说,反正事情是私人的,所以你需要一个二传手。或者,你可以让 B 成为 A 的朋友,或者给 B 一个指向事物成员的指针。
相关文章:
- 在类函数中初始化外部作用域变量
- c++ 在非类函数中使用类变量
- 为什么我不能在返回 const 的布尔函数中为类成员变量赋值?C++
- 在类成员函数中声明类成员变量
- 将变量从 main 传递到公共类函数?
- 类函数C++无法更改变量
- 为什么我的类函数不使用我的全局变量?
- C++ 在头文件或构造函数中初始化 const 类成员变量?
- 类函数不会永久更改成员变量
- 我如何实现从其基类获取变量的构造函数
- 创建一个简单的类及其变量和函数不断返回" segmentation fault (core dumped)"、C++
- 如何从doxygen输出中排除类的无证件成员函数/变量
- 是否可以将类成员变量设置为类函数的结果?
- 在定义变量时调用类函数
- 修改类中调用另一个类函数的变量
- 访问实例化类的变量/函数
- 构造函数不更新类成员变量
- 如何将类成员(变量?)传递给函数
- 具有类构造函数和类成员变量的意外输出值
- 类函数/变量在使用之前必须声明