CHAPTER12
UML模型的C++实现 12.1 概述
图12-1 Account类
// File : Account.h
class Account { public: // 默认的构造函数和析构函数 Account(); ~Account();
// 用户定义的方法
void PrintAmount(); private: //用户定义的属性 int amount;
};
// File: Account.cpp #include \Account::Account() { // 构造函数体 }
第12286 U ML与软件建模
Account::~Account() { // 析构函数体 }
void Account::PrintAmount() { //此处方法体由程序人员自己给出,或根据UML模型中的其他信息自动生成 }
12.2 属性和方法的映射
virtual 类型名 方法名([参数表]) = 0; 类别 形式参数名:类型表达式 = 默认值
图12-2 爆炸类、核爆炸类和爆炸碎片类之间的关系
// File:Detonation.h class Detonation {
public: virtual ~Detonation( );
virtual const Location& location( ) const; protected:
Detonation( );
Virtual void location(const Location& loc);
private: Location location; };
// File: NuclearDetonation.h
class NuclearDetonation : public virtual Detonation { public:
287 第12章 UML模型的C++实现
NuclearDetonation( );
NuclearDetonation(const NuclearDetonation&);
~NuclearDetonation( );
NuclearDetonation& operator = (const NuclearDetonation&);
protected: private: DebrisPatch* debrisPatch; }
// File: DebrisPatch.h class DebrisPatch { public:
DebrisPatch( );
DebrisPatch(const DebrisPatch&);
~DebrisPatch( );
DebrisPatch operator = (const DebrisPatch&);
protected: private: NuclearDetonation* nuclearDetonation; };
12.3 泛化与特化关系的映射
图12-3 Employee及其子类之间的关系
// File: VestedHourlyEmployee.h #include \#include \
... class VestedHourlyEmployee: virtual public VestedEmployee, virtual public HourlyEmployee { ...
288 U ML与软件建模
}
12.4 关联关系的映射
表12-1 关联关系映射表
关联多重性 1 * *{ordered} C++结构 指针 指针集合 有序的指针集合 12.4.1 单向关联的映射 12.4.2 双向关联的映射
Customer0..1cust1bookBook
图12-4 顾客和书之间的关系
// File: Customer.h ...
class Customer { friend class Book; public: ...
// Association accessor methods void setBook(Book* newBook); const Book* getBook() const;
protected: ... private: };
...
//File: Book.h ...
#ifndef CUSTOMER_H #include \#endif
...
// Association attribute storage Book* bookptr;
289 第12章 UML模型的C++实现
...
class Book {
friend class Customer; public:
...
// Association accessor methods void setCust(Customer* newCust); const Customer* getCust() const;
... protected: ... private: }; ...
...
// Association attribute storage Customer* custPtr;
12.4.3 强制对可选关联的映射
A1a0..1bB
图12-5 类A和B之间的可选关联
// File: B.h ...
class B { friend class A; public:
// Default constructor/destructor B(const A& a);
... }; ...
12.4.4 强制对强制关联的映射
A1a1bB
图12-6 A和B之间的强制对强制关联