我知道关联和聚合以及组合和概括它们的定义。继承是“是一种”关系,而构成是“有一种”关系。
Class A {
}
Class B extends A { // this is Generalization
}
Class C {
A ob; // this is composition
}
现在我的问题是如何根据编程代码显示聚合和简单关联。 ?
答案 0 :(得分:1)
我怀疑你真正的问题与构图与聚合有关。您可以考虑所有权方面的差异,但真正的区别(对于我的钱)是控制聚合对象生命周期的因素。
在作文中。当组合对象被销毁时,其包含的部分或类与它一起被销毁。通过聚合,包含的对象的生命周期可以独立于包含对象。在代码中。这取决于组件对象是由值还是引用指定的。聚合有通过引用(或示例中的指针)完成。如果它是按值完成的,那么组件部分将超出范围并被包含对象销毁,因此是组合。
因此,在这种情况下,Engine是一个组合示例,而Battery是Aggregation的一个示例。
#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;
}
道歉,如果这不是最好的例子,但希望它说明了重点。
答案 1 :(得分: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
}
}