gpt4 book ai didi

c++ - 从另一个类调用一个类方法

转载 作者:行者123 更新时间:2023-11-30 02:49:25 26 4
gpt4 key购买 nike

我想在类 A 的方法成员中更改类 B 的变量成员。示例:

A.h:
class A
{
//several other things
void flagchange();
}
A.cpp:
void A::flagchange()
{
if (human) Bobj.flag=1;
}

我知道我需要一个类 B 的对象来更改 B 的变量成员,但是 B 的对象在 A 中不可访问。是否可以通过指针实现?

最佳答案

but objects of B are not reachable in A

如果类 A 无法访问类 B 的对象,则您无法修改它们。重构设计后,应将其作为参数传递给函数:

class A {
//several other things
void flagchange(B& obj) {
if (human)
obj.flag = 1;
}
};

I want to be able to toggle the flag from a method of class A for every object of B

您应该在 B 中将您的 flag 公共(public)变量声明为 static:

class B {
public:
static int flag;
};

int B::flag = 0;

然后,从 A 内部:

class A {
//several other things
void flagchange() {
if (human)
B::flag = 1;
}
};

关于c++ - 从另一个类调用一个类方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21200015/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com