0

我知道关联和聚合以及组合和泛化它们的定义是什么。继承是“是”关系,组合是“具有”关系。

Class A {
}

Class B extends A { // this is Generalization
}

Class C {
 A ob;  // this is composition
}

现在我的问题是如何根据编程代码显示聚合和简单关联。?

4

2 回答 2

1

我怀疑您的真正问题与组合与聚合有关。您可以考虑所有权方面的差异,但真正的区别(为了我的钱)是控制聚合对象的生命周期的东西。

在组成。当组合对象被销毁时,其包含的部分或类也随之被销毁。通过聚合,包含对象的生命周期可以独立于包含对象。在代码中。这归结为组件对象是由值还是引用指定。聚合必须通过引用(或示例中的指针)来完成。如果它是按值完成的,则组件部分将超出范围并与包含对象一起销毁,因此是组合。

所以在这种情况下,引擎是组合的一个例子,电池是聚合的一个例子。

#include <iostream>

using namespace std;

class Engine
{
   public:

      Engine() {cout << "Engine created\n";};
     ~Engine() {cout << "Engine destroyed\n";};
};


class Battery
{
   public:

      Battery() {cout << "Battery created\n\n";};
     ~Battery() {cout << "\nBattery destroyed\n";};
};

class Car
{
   private:

      Battery *bat;
      Engine  eng;  //Engine will go out of scope with Car

   public:

      Car(Battery* b) : bat(b) {cout << "Car created\n";};
     ~Car() {cout << "Car destroyed\n";};

       void drive(int miles) {/*...*/};
};



int main(int argc, char *argv[])
{
   //a Battery lifecycle exists independently of a car
   Battery* battery = new Battery();

   //but a car needs to aggregate a Battery to run
   Car* car1 = new Car(battery);

   car1->drive(5);

   //car1 and its Engine destroyed but not the Battery
   delete car1;

   cout << "---------------\n";

   //new car, new composed Engine, same old Battery
   Car* car2 = new Car(battery);

   car2->drive(5);
   delete car2;

   //destroy battery independently of the cars
   delete battery;

}

抱歉,如果这不是最好的例子,但希望它说明了要点。

于 2009-06-12T14:47:48.430 回答
0

我不确定您到底要在这里做什么,但我会建议以下示例:

聚合

public class A { }
public class List<A> { }  // aggregation of A

协会(使用)

public class A
{
    public void AMethod() { ... }

public class B
{
    public void BMethod( A a )
    {
         a.AMethod();  // B uses A
    }
}
于 2009-06-12T01:29:52.313 回答