ChangeUnidirectionalAssociationToBidirectional(将单向关联改为双向关联)

来源:互联网 发布:jquery post提交 php 编辑:程序博客网 时间:2024/06/08 15:17
#ifndef CHANGEUNIASSOCTOBID_H_#define CHANGEUNIASSOCTOBID_H_#include <set>#include <string>class Customer;class Order{public:Order(std::string id = "", Customer* cus = NULL);void setCustomer(Customer& arg);std::string getCustomer();std::string getId() const;bool operator<(const Order& arg) const;private:std::string id;Customer* customer;};class Customer{public:Customer(std::string arg);void add(Order& arg);void del(Order& arg);const std::string getName() const;void getOrder();private:std::string name;std::set<Order> orders;};#endif /* CHANGEUNIASSOCTOBID_H_ */


#include "ChangeUniAssocToBid.h"#include <iostream>using namespace std;Order::Order(string id, Customer* cus):id(id),customer(cus){}string Order::getCustomer(){return customer->getName();}bool Order::operator <(const Order& arg) const{return this->id < arg.id;}void Order::setCustomer(Customer& arg){if(this->customer){this->customer->del(*this);}this->customer = &arg;this->customer->add(*this);}string Order::getId() const{return id;}Customer::Customer(string arg):name(arg){}const string Customer::getName() const{return name;}void Customer::add(Order& arg){orders.insert(arg);}void Customer::del(Order& arg){orders.erase(arg);}void Customer::getOrder(){set<Order>::iterator it = orders.begin();while(it != orders.end()){string id = (*it).getId();cout<<id<<endl;it++;}}void ChangeUniAssocToBid(){Order o1("1");Order o2("2");Customer c1("Tom");Customer c2("Jerry");o1.setCustomer(c1);o2.setCustomer(c2);cout<<c1.getName()<<" has order "<<endl;c1.getOrder();cout<<c2.getName()<<" has order "<<endl;c2.getOrder();o1.setCustomer(c2);cout<<c1.getName()<<" has order "<<endl;c1.getOrder();cout<<c2.getName()<<" has order "<<endl;c2.getOrder();}



0 0