个性化阅读
专注于IT技术分析

C++聚合(HAS-A关系)

在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("C-146, Sec-15", "Noida", "UP");  
    Employee e1 = Employee(101, "Nakul", &a1);  
            e1.display(); 
   return 0;
}

输出:

101 Nakul C-146, Sec-15 Noida UP
赞(0)
未经允许不得转载:srcmini » C++聚合(HAS-A关系)

评论 抢沙发

评论前必须登录!