2012-01-24 419 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关键字和取消引用参数作为运算符重载的一部分,老实说,我不知道为什么该版本修复了这个问题,而我的(请参阅原文后编辑)不是! –