我有一个类(组合)(有一个关系)如下:
class AP
是一个更大的类,包含class A
的对象。 AP
还有一个 state
变量作为它的成员。
问题:我可以在其他组合成员中访问 AP 的成员 'state'
吗? (即 A
类型的内部对象)?
这是代码
class A {
int i;
public:
void set(int x)
{ i = x; }
int get()
{ return i; }
void process()
{
cout << ::this->get() << endl; //// how to access AP's state variable here ?
}
};
class AP
{
A a;
int state;
public:
void process()
{ a.process(); }
void set()
{ state = 1; }
int get()
{ return state; }
};
/// AP contains (or owns an object of type A)
/// I need to access AP's state value in object of type A (which is ap's member)
int main()
{
AP ap; //
ap.set(); // set state value for AP
cout << " get " << ap.get() << endl; // get state value for AP
ap.process(); /// calls a.process --> this must access ap's state value
return 0;
}
有可能的解决方案,例如:
传递对自身的引用然后访问值。
只是简单地在 process() 函数中传递
state
的值。 (ap.process(state)
)
但我想知道我是否可以直接访问具有组合 (has-a) 的其他成员中的类的成员变量 [参见 class A::process()
方法。
最佳答案
您要问的是“我可以在使用“有一个”概念设计的对象上使用“是一个”概念吗?
简短的回答,不。
长答案: 有时,但前提是它是静态的。否则,“A”无法在没有上下文的情况下访问“AP”的非静态成员。
class A {
public:
int p;
void process() {
p = AP::as; /* static object, okay! */
p = AP::ap; /* compiler error, where's the instantiated AP to go along with it??? */
}
};
class AP {
public:
int ap;
A a;
static int as;
};
“static”修饰符将指定的对象设置为单个实例。请记住,当您开始使用线程时:所有线程都使用相同 实例,这会引入数据竞争!恰当的例子:errno
在 c++11 之前;有很多关于 errno
和线程令人头疼的 google 引用资料。因为只有一个 AP::as
实例,所以您的 A
确切知道在哪里可以找到它(甚至可能是第一个访问它的人)。
但是由于 AP::ap
没有 static 修饰符,它必须实例化 AP
的实例。如上所示访问它会导致编译器错误,因为编译器不知道在哪里可以找到 AP::ap
对象。它需要一个 AP
。因此,您可以在此处为已实例化的 AP
提供引用 ,如下所示:AP obj; p = obj.ap;
(或者您决定提供实例化 AP
的其他方式,例如通过引用或指针或其他方式)。
所有这一切都是因为,考虑到可能存在零个、一个或多个 AP
对象 (AP aap; AP bap; A a; a.process();
,你到底想要哪个?示例:
int main() {
A a;
a.process(); // Now what should 'a' try to access since there is no instantiated version of 'AP' ?
AP aap;
AP bap;
a.process(); // Okay now there are two APs... which one did you want 'a' to access?
}
“有一个”概念与“是一个”概念完全不同(事实上,“有一个”概念不是继承,因为你已经标记了这个问题!)。
关于c++ - 由组合的其他成员访问 'has-a' 关系中的成员,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27789933/