2015-01-04 25 views
-6

我尋找到實現該場景的最佳方式:最好的方式,如果其它目的之一是真還是假

我有4個對象具有在應用的流量有時它們被設置布爾成員根據情況設定爲真,有時設定爲假;

然後,我有最終的功能,得到1這個對象,並需要檢查,如果在其他3個對象之一,他們有成員設置爲true。

問題是,我知道該怎麼做骯髒的檢查,我正在尋找在這裏更清潔的方式是我最終的功能代碼:

class Obj 
{ 
public : 
    Obj(int _id) : id(_id) 
    bool status; 
    int id // only 4 objects are created 0,1,2,3 
} 

m_obj0 = new Obj(0) ; 
m_obj1 = new Obj(1) ; 
m_obj2 = new Obj(2) ; 
m_obj3 = new Obj(3) ; 

bool check(Obj* obj) 
{ 
    if(obj->id == 0) 
    { 
     if(m_obj1->status || m_obj2->status || m_obj3->status) 
     { 
      return true; 
     } 
     return false; 
    }else if(obj->id == 1)(
     if(m_obj0->status || m_obj2->status || m_obj3->status) 
     { 
      return true; 
     } 
     return false; 
    }else if(obj->id == 2)(
     if(m_obj0->status || m_obj1->status || m_obj3->status) 
     { 
      return true; 
     } 
     return false; 
    }else if(obj->id == 3)(
     if(m_obj0->status || m_obj1->status || m_obj2->status) 
     { 
      return true; 
     } 
     return false; 

} 

有沒有做到這一點檢查更短的和更清潔的方式功能?

+1

如果你會很好提到了這是哪種編程語言。 – JJJ 2015-01-04 12:24:12

+0

我做了一些C++,但它真的沒關係 – user63898 2015-01-04 12:27:51

回答

3

您可以將m_obj設置爲數組。然後使用一個循環來檢查

bool check(Obj* obj) 
{ 
    for (int i = 0; i < 4; i ++) { 
     if (obj->id == i) continue; 
     if (m_obj[i]->status == true) 
      return true; 
    } 
    return false; 
} 

或加在一起,然後減去m_obj [obj-> ID] - > status.Check結果爲零或不

bool check(Obj* obj) 
{ 
    int result = m_obj[0]->status+m_obj[1]->statusm_obj[2]->status 
       +m_obj[3]->status-m_obj[obj->id]->status; 
    return (result!=0); 
} 
+0

它的選項,順便說一句,我只需要其中一個是真的 所以你可以添加break;在第一次找到之後。 但我徘徊,如果有更好的辦法..謝謝! – user63898 2015-01-04 12:29:12

+1

@ user63898該函數在第一次查找後返回true,返回後不需要中斷。 – BlueMandora 2015-01-04 12:32:29

+0

什麼是更有效的,如果我知道我只有4個對象 檢查他們,因爲我做的循環檢查? – user63898 2015-01-04 12:51:17

相關問題