2012-01-24 48 views
0

我已經定義了類的「結果」和「Bin」。 我想將類型數組的數組傳遞給Bin構造函數,以便將該數組的每個元素添加到一組「結果」,它是Bin類的成員屬性。如何將數組的元素添加到集合

//Bin.h 
class Bin { 
private: 
    std::set<Outcome> outcomeset; 
public: 
    Bin(); 
    Bin(Outcome Outcs[], int numberofelements); 
    Bin(std::set<Outcome> Outcs); 
    void add(Outcome Outc); 
    std::string read(); 

}; 

//In Bin.cpp 

Bin::Bin(Outcome outcs[], int numberofelements) { 
    int i; 
    for (i=0;i<(numberofelements-1);i++) { 
     outcomeset.insert(outcs[i]); //When this LIne is commented out, no compile errors! 
    } 
} 

這會導致VS2010中的錯誤鏈接回庫文件。我一直無法在網上或在「The Big C++」教科書中找到任何東西。這是這種功能的完全錯誤的實現嗎?或者我錯過了一些相當基本的東西?

對於好奇的我從這個免費教科書實施這一爲「輪盤賭」問題的一部分http://www.itmaybeahack.com/homepage/books/oodesign.html

感謝您的幫助!

編輯:我已經添加了(相當長的)錯誤文本到引擎收錄,在這裏:http://pastebin.com/cqe0KF3K

EDIT2:我已經實現了== =和<運營商的結果類,並在同一行依舊!不編譯。這裏是實現

//Outcome.cpp 
bool Outcome::operator==(Outcome compoutc) { 
    if (mEqual(compoutc) == true) { 
    return true; 
} 
else { 
    return false; 
} 
} 

bool Outcome::operator!=(Outcome compoutc) { 
if (mEqual(compoutc) == false) { 
    return true; 
} 
else { 
    return false; 
} 
} 

bool Outcome::operator<(Outcome compoutc) { 
if (odds < compoutc.odds) { 
    return true; 
} 
else { 
    return false; 
} 
} 

EDIT3:實現比較運算符與去引用參數和const標記,現在它編譯!

+0

你的類'Outcome'不提供比較運算符。 –

+0

'我<(numberofelements-1)'看起來像一個錯誤的錯誤。如果列表中有3個元素,我將[0,1],你會錯過索引2. – Thanatos

+0

我現在已經爲Outcome類實現了==!=運算符,上面的Bin構造函數仍然不能編譯。 (謝謝你的回覆) @Thanatos,漂亮的眼睛,我刪除了它,但它對編譯錯誤沒有任何影響,我會發布一些錯誤信息到原始文章。 ! –

回答

0

您需要爲要插入集合的類定義operator<

還要注意,而不是外在的循環,你可能會更好過使用一對「迭代器」(指針,在這種情況下)的,實際上初始化設定:

#include <set> 
#include <string> 

class Outcome { 
    int val; 
public: 
    bool operator<(Outcome const &other) const { 
     return val < other.val; 
    } 
    Outcome(int v = 0) : val(v) {} 
}; 

class Bin { 
private: 
    std::set<Outcome> outcomeset; 
public: 
    Bin(); 

    // Actually initialize the set: 
    Bin(Outcome Outcs[], int n) : outcomeset(Outcs, Outcs+n) {} 
    Bin(std::set<Outcome> Outcs); 
    void add(Outcome Outc); 
    std::string read(); 

}; 

int main() { 
    // Create an array of Outcomes 
    Outcome outcomes[] = {Outcome(0), Outcome(1) }; 

    // use them to initialize the bin: 
    Bin b((outcomes),2); 

    return 0; 
} 
+0

謝謝!我將閱讀關於使用const關鍵字和取消引用參數作爲運算符重載的一部分,老實說,我不知道爲什麼該版本修復了這個問題,而我的(請參閱原文後編輯)不是! –