프로그래밍 코드 측면에서 집계를 표시하는 방법은 무엇입니까?
-
13-09-2019 - |
문제
나는 연관과 집합, 구성과 일반화에 대해 정의에 따라 무엇인지 알고 있습니다.상속은 "is a" 관계이고 구성은 "has a" 관계입니다.
Class A {
}
Class B extends A { // this is Generalization
}
Class C {
A ob; // this is composition
}
이제 내 질문은 프로그래밍 코드 측면에서 집계 및 단순 연관이 어떻게 표시되는지입니다.?
해결책
귀하의 실제 질문은 구성과 집계와 관련이 있다고 생각됩니다.소유권 측면에서 차이점을 생각할 수 있지만 실제 차이점은 (내 돈으로) 집계된 개체의 수명 주기를 제어하는 것입니다.
구성.구성된 객체가 삭제되면 포함된 부분이나 클래스도 함께 삭제됩니다.집계를 사용하면 포함된 개체의 수명이 포함하는 개체와 독립적일 수 있습니다.코드에서.이는 구성 요소 개체가 값 또는 참조로 지정되는지 여부에 따라 달라집니다.집합 가지다 참조(또는 예제와 같은 포인터)로 수행됩니다.값에 따라 수행되면 구성 요소 부분은 범위를 벗어나 포함 객체와 함께 소멸되므로 구성이 됩니다.
따라서 이 경우 엔진은 구성의 예이고 배터리는 집계의 예입니다.
#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;
}
이것이 최선의 예가 아니라면 사과드립니다. 그러나 이것이 주요 요점을 설명해주기를 바랍니다.
다른 팁
당신이 여기서 무엇을하고 있는지 정확히 잘 모르겠지만 다음 예제를 제안합니다.
집합
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
}
}
제휴하지 않습니다 StackOverflow