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