對於一對多的示例,可以想象一個賬戶可以多次申購。在申購的時候沒有固定上限,下限為0,那么就可以使用容器類(container class)來搞,最常見的就是vector了。

下面我們來看一個“一對多”的例子
Account.h
1 #include <cstdlib> 2 #include <vector> 3 #include "Bid.h" 4 using namespace std; 5 6 class Account 7 { 8 public: 9 void setBid(Bid*); 10 int calcAmount(); 11 private: 12 vector<Bid*> bidObj; 13 };
聲明一個存放申購交易對於指針的vector對象。然后類Account中的函數setBid設計了一個公有操作,讓外界用來傳入申購交易對象的指針,以便讓賬戶對象將申購交易對象指針存入vector對象中。
Account.cpp
1 #include "Account.h" 2 3 void Account::setBid(Bid *theBid) 4 { 5 bidObj.push_back(theBid); 6 } 7 8 int Account::calcAmount() 9 { 10 int size,theAmount=0; 11 size=bidObj.size(); 12 for(int i=0;i<size;i++) 13 theAmount=theAmount+bidObj[i]->getAmount(); 14 return theAmount; 15 }
Bid.h
1 class Bid 2 { 3 public: 4 void setAmount(int); 5 int getAmount(); 6 private: 7 int amount; 8 };
Bid.cpp
1 #include "Bid.h" 2 3 void Bid::setAmount(int theAmount) 4 { 5 amount=theAmount; 6 } 7 8 int Bid::getAmount() 9 { 10 return amount; 11 }
main.cpp
1 #include <cstdlib> 2 #include <iostream> 3 #include "Bid.h" 4 #include "Account.h" 5 using namespace std; 6 7 int main(int argc, char *argv[]) 8 { 9 Bid *myBid; 10 Account myAccount; 11 int theAmount; 12 int choice; 13 14 do 15 { 16 cout << "請輸入申購金額: "; 17 cin >> theAmount; 18 myBid=new Bid; 19 myBid->setAmount(theAmount); 20 myAccount.setBid(myBid); 21 cout << "1(繼續), 2(結算) ..."; 22 cin >> choice; 23 cout << endl; 24 } while(choice==1); 25 26 cout << "總投資金額為: " 27 << myAccount.calcAmount() << endl << endl; 28 29 system("PAUSE"); 30 return EXIT_SUCCESS; 31 }
下面我們來畫一下UML圖,並且用UML自動生成C++代碼來做一個比較
畫法一:

生成代碼對比
Account.h

沒有達到預期,多生成了成員變量,如果在類圖里面寫明了某個指針變量的話,那么在關聯關系的端點處就不能再標示這個成員變量了,否則就會重復生成
見UML類圖詳解_關聯關系_多對一中的畫法二,也是因為這個導致了沒有達到預期
Bid.h

達到預期
畫法二:

生成代碼對比
Account.h

達到預期
Bid.h

達到預期
畫法三:

生成代碼對比
Account.h

沒有達到預期
Bid.h

達到預期
綜上所述,在實際畫圖的時候采用畫法二才能保證正確,一旦類圖里面包含了一次成員那么在關聯端點再聲明一次的話就會重復,另外如果不在類圖里面包含一次成員而在關聯端點處聲明一次的話生成的代碼比較傻,很多情況下無法滿足我們的要求。所以我們就是把成員都在類圖里面包含進去,關聯端點處就是聲明一下多重性,而不要再聲明成員就可以了。
