C++聚合

在C++中,聚合是一個進程,一個類將另一個類定義爲實體引用(一個類作爲另一個類的成員)。 這是另一種重用類的方法。 它是一種表示HAS-A關係的關聯形式。

C++聚合示例

下面來看看一個聚合的例子,其中Employee類有Address類的引用作爲數據成員。 這樣,它可以重用Address類的成員。

#include <iostream>  
using namespace std;  
class Address {  
    public:  
   string addressLine, city, state;    
     Address(string addressLine, string city, string state)    
    {    
        this->addressLine = addressLine;    
        this->city = city;    
        this->state = state;    
    }    
};  
class Employee    
    {    
        private:  
        Address* address;  //Employee HAS-A Address   
        public:  
        int id;    
        string name;    
        Employee(int id, string name, Address* address)    
       {    
           this->id = id;    
           this->name = name;    
           this->address = address;    
       }    
     void display()    
       {    
           cout<<id <<" "<<name<< " "<<     
             address->addressLine<< " "<< address->city<< " "<<address->state<<endl;    
       }    
   };   
int main(void) {  
    Address a1= Address("Renmin Road-15","Haikou","UP");    
    Employee e1 = Employee(101,"Beijing",&a1);    
            e1.display();   
   return 0;  
}

執行上面代碼,得到以下結果 -

101 Beijing Renmin Road-15 Haikou UP