我已经定义了类'结果'和'Bin'。 我试图将一个类型的Outcome数组传递给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
将其作为“轮盘赌”问题的一部分来实施感谢您的帮助!
编辑:我已将(相当冗长的)错误文本添加到pastebin中,此处:http://pastebin.com/cqe0KF3K
EDIT2:我已经实现了==!=和&lt;结果类的运算符,同一行仍然无法编译。以下是实现
//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 :(得分: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;
}