c++ - 由组合的其他成员访问 'has-a' 关系中的成员

标签 c++ inheritance

我有一个类(组合)(有一个关系)如下:

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;
}

有可能的解决方案,例如:

  1. 传递对自身的引用然后访问值。

  2. 只是简单地在 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/

相关文章:

c++ - 自定义大括号初始值设定项

c++ - 移植的 C header 中的 NULL 与 nullptr

c++ - 如何使用 oci 或任何其他库以 sys 帐户登录 oracle

Objective-C:实例变量超出调试器的范围

ios - 如何在多个ViewController中使用NSFetchedResultsControllerDelegate而不重复 Controller 代码?

嵌套 HashMap 中的java泛型/继承

c++ - AVX指令中寄存器和指针的客观区别

c++ - 为什么在下面的程序中没有调用复制构造函数?

c# - 创建可扩展属性类 (OOP)

ruby - Ruby 子类实例变量可以_overwrite_ 父类(super class)的(同名)吗?