2016-01-11 39 views
1

我有一個小問題,Visual Studio編譯器似乎沒有被打擾,但在eclipse和g ++中。operator <=重載2個類並轉換ctor

我有2個班,卡和CardDeck。我確實有運營商< = 2 Carddecks作爲參數,不適用於2卡。我有一個轉換ctor,將卡轉換成甲板。

所以,問題是,當我這樣做:

card1 <= card2 

這確實在視覺做工精細,它轉換左側部分甲板上,然後將右,然後做比較。

在G ++,它說:

no match for 'operator<=' (operand types are 'Card' and 'Card') 

但不應該有一個。正如我所說我想要轉換器能夠把握雙方並進行比較?

對此有何解釋和解決辦法?

編輯(操作和構造函數聲明和代碼):

CardDeck(const Card&); 
friend bool operator<=(const CardDeck&, const CardDeck&); 

CardDeck::CardDeck(const Card& card){ 
    _Deck.push_back(card); 
} 
+0

代碼說超過一千字。請嘗試創建[最小化,完整和可驗證示例](http://stackoverflow.com/help/mcve)並向我們顯示。 –

+0

您的運營商<='是會員還是非會員? – TartanLlama

+0

非會員作爲朋友 – KittyT2016

回答

0

這裏有一個快速&骯髒的東西,我認爲你正在嘗試做的:

#include <iostream> 

struct Element 
{ 
    int x; 
    Element() :x(0) {} 
    virtual ~Element() {} 
}; 

struct Container 
{ 
    Element elems[10]; 
    int n; 
    Container() { n=0; } 
    Container(const Element &e) { elems[0]=e; n=1; } 
    virtual ~Container() {} 
    friend bool operator<=(const Container &l, const Container &r); 
}; 

bool operator<=(const Container &l, const Container &r) 
{ 
    if (l.n<=r.n) { std::cout << "less/equ\n"; return true; } 
    else { std::cout << "greater\n"; return false; } 
} 

int main(int argc, const char *argv[]) 
{ 
    //Container container; 
    Element a, b; 
    if (a<=b) std::cout << "okay\n"; else std::cout << "fail\n"; 
    return 0; 
} 

它正常工作與海灣合作委員會。

+0

似乎我寫的東西在這種情況下也應該起作用,非常奇怪。我真的沒有看到區別。 – KittyT2016

0
Deck(card1) <= Deck(card2) 

operator<= (operand types are 'Card' and 'Card')覆蓋,因爲你使用的(平均),在card1 <= card2表達。你的代碼有架構錯誤。


更新

struct Card 
{ 
    bool operator<(const Card& right) const; 
}; 

struct Deck 
{ 
    std::vector<Card> m_arr; 

    Deck() = default; 
    Deck(const Card& conversion) 
    { 
     m_arr.push_back(conversion); 
    } 
    bool operator<(const Deck& right) const; 
}; 

bool Card::operator<(const Card& right) const 
{ 
    return false; 
} 
bool Deck::operator<(const Deck& right) const 
{ 
    bool result = false; 
    if(m_arr.size() < right.m_arr.size()) 
    { 
     result = true; 
    } 
    else if(!m_arr.empty() && m_arr.size() == right.m_arr.size()) 
    { 
     result = true; 
     std::vector<Card>::const_iterator it = right.m_arr.begin(); 
     std::vector<Card>::const_iterator it2 = m_arr.begin(); 
     for(; it2 != m_arr.end(); ++it, ++it2) 
     { 
      if((*it) < (*it2)) 
      { 
       result = false; 
       break; 
      } 
     } 
    }  
    return result; 
} 
+0

正如我在其他評論中寫的,所有其他比較運算符(僅使用<=)在方程的每一邊都可以正常工作。我該如何解決它? – KittyT2016

+0

@ KittyT2016,你如何從邏輯上解釋一副牌的比較......? – rikimaru2013

+0

deck1 <= deck2如果deck1中的每張卡片都在deck2中(deck2可以擁有deck1以上的所有卡片)。 – KittyT2016