首先要注意在C++中,不像在Java中,用戶可以定義值類型。這意味着對於routing_entry有2^32 * 2^32 * 2^8個可能的值。如果你願意,你可以將routing_entry想象成一個72位的原始類型,儘管你必須小心這個類比。
因此,在Java中route
可以爲空,並且對於routing_entry
變量有2^32 * 2^32 * 2^8 + 1有用的不同值。在C++中,它不能爲空。在Java中「空」可能意味着返回一個空引用。在C++中,只有指針可以爲空,並且routing_entry
不是指針類型。因此,在這種情況下,你的代碼中的「空」意味着「我不知道這個東西有什麼價值,因爲我從來沒有初始化它或分配給它」。
在Java中,將在堆上分配一個routing_entry
對象。在C++中,除非必須這麼做,否則不需要這樣做,因爲C++中的內存管理需要付出努力。
你有幾個(好)選項:
1)字段添加到路由表項,以表明它已被初始化。可能這不會讓的,因爲你的執行填充和對齊需求結構的任何更大,:
struct routing_entry {
unsigned long destSeq; // 32 bits on Win32. Could be different.
unsigned long nextHop // 32 bits on Win32. Could be different.
unsigned char hopCount; // 8 bits on all modern CPUs. Could be different.
unsigned char initialized; // ditto
};
爲什麼不使用布爾?因爲標準有用地允許sizeof(bool) != 1
。 bool完全可以作爲int來實現,特別是如果你有一個古老的C++編譯器。這會讓你的結構更大。
然後確保結構也是在你的函數inited 0值,是在棧上的,而不是什麼垃圾:
routing_entry Cnode_router_aodv::consultTable(unsigned int destinationID) {
routing_entry route = {};
if (routing_table.find(destinationID) != routing_table.end())
route = routing_table[destinationID];
return route; // will be "empty" if not found
}
,並確保在地圖中所有entriess有初始化字段設置爲非零。呼叫者然後檢查初始化。
2)使用現有字段的「魔術」值作爲標記。
假設爲了論證,你從不處理hopCount 0的路由。然後只要你如上所述0初始化,調用者可以檢查hopCount!= 0。類型的最大值也是好標誌值 - 因爲你限制你的路由爲256跳,所以你不會將它們限制在255跳以內。而不必記住這個呼叫者的方法添加到結構:
struct routing_entry {
unsigned long destSeq; // 32 bits
unsigned long nextHop // 32 bits
unsigned char hopCount; // 8 bits
bool routeFound() { return hopCount != (unsigned char)-1; }
};
然後你初始化像這樣:
routing_entry route = {0, 0, -1};
,或者如果你擔心,當你更改順序會發生什麼或將來字段數:
routing_entry route = {0};
route.hopCount = -1;
,且調用者:
routing_entry myroute = consultTable(destID);
if (myroute.routeFound()) {
// get on with it
} else {
// destination unreachable. Look somewhere else.
}
3)調用者通過指針或非const引用傳入routing_entry
。被調用者填寫答案,並返回一個值,表示它是否成功。這通常被稱爲「外部參數」,因爲它有點模擬返回一個布爾型的函數返回routing_entry
和。
bool consultTable(unsigned int destinationID, routing_entry &route) {
if (routing_table.find(destinationID) != routing_table.end()) {
route = routing_table[destinationID];
return true;
}
return false;
}
調用程序:
routing_entry route;
if (consultTable(destID, route)) {
// route found
} else {
// destination unreachable
}
順便說一句,使用的地圖,當你的代碼,因爲它是查找該ID兩次。您可避免這種 如下,雖然它不可能使一個明顯的區別,以您的應用程序的性能:
map< unsigned long int, routing_entry >::iterator it =
routing_table.find(destinationID);
if (it != routing_table.end()) route = *it;
謝謝大家,我收到了很多非常有幫助的評論,他們真的打開了我的眼睛。我是C++的新手,但我堅持使用它,因爲我正在爲我的主人使用遺留代碼。 最後,我必須選擇一個答案,但我贊成所有那些啓發了我的答案。再次感謝:) – sabbour 2009-06-19 11:44:37