【发布时间】:2016-11-15 18:39:42
【问题描述】:
这里有枚举类:
enum class wahl {
schere , stein , papier
};
然后我重载运算符
bool operator<(wahl &wahl1, wahl &wahl2) {
switch (wahl1) {
case wahl::papier: {
if (wahl2 == wahl::schere) {
return true; break;
} //papier < schere
else if (wahl2 == wahl::stein) {
return false; break;
} //papier > stein
else {
return false; break;
}
}
case wahl::schere: {
if (wahl2 == wahl::stein) {
return true; break;
} //schere < stein
else if (wahl2 == wahl::papier) {
return false; break;
} //schere > papier
else {
return false; break;
}
}
case wahl::stein: {
if (wahl2 == wahl::papier) {
return true; break;
} //stein < papier
else if (wahl2 == wahl::schere) {
return false; break;
} //stein > schere
else {
return false; break;
}
}
}
};
bool operator > (const wahl wahl1, const wahl wahl2) {
switch (wahl1) {
case wahl::papier: {
if (wahl2 == wahl::schere) {
return false; break;
}
// papier < schere
else if (wahl2 == wahl::stein) {
return true; break;
} //papier > stein
else {
return false; break;
}
}
case wahl::schere: {
if (wahl2 == wahl::stein) {
return false; break;
} //schere < stein
else if (wahl2 == wahl::papier) {
return true; break;
} //schere > papier
else {
return false; break;
}
}
case wahl::stein: {
if (wahl2 == wahl::papier) {
return false; break;
} //stein < papier
else if (wahl2 == wahl::schere) {
return true; break;
} //stein > schere
else {
return false; break;
}
}
}
};
我有另一个班级,名为 player :
class player {
wahl pl_wahl;
int pl_score;
char* pl_name;
public:
player() {}
player(int score, wahl wahl, char* name) :
pl_wahl{ wahl }, pl_score{ score }, pl_name{ name } {}
wahl pl_get_wahl() {
return pl_wahl;
}
char* pl_get_name() {
return pl_name;
}
int &pl_get_score() {
return pl_score;
}
};
在这里我使用了比较器:
class game {
player game_player1, game_player2, game_momentan_gewinner;
int game_score_max;
public:
game() {}
game(player player1, player player2, int score_max) :
game_player1{player1},
game_player2{player2},
game_score_max{ score_max } {}
void vergleichen() {
if (game_player1.pl_get_wahl() > game_player2.pl_get_wahl()) {
game_momentan_gewinner = game_player1;
std::cout << "Gewinner dieser Runde ist Player 1 : " <<
game_momentan_gewinner.pl_get_name() << std::endl;
}
if (game_player1.pl_get_wahl() < game_player2.pl_get_wahl()) {
game_momentan_gewinner = game_player2;
std::cout << "Gewinner dieser Runde ist Player 2 : " <<
game_momentan_gewinner.pl_get_name() << std::endl;
}
else {
std::cout << "Remis" << std::endl;
}
}
};
我遇到的问题是枚举将作为 int 进行。如果我要求比较两个枚举变量,结果将取决于 int 值而不是取值,我用重载运算符设置。
有什么方法可以让编译器停止使用枚举变量的 int 值,并以我想要的方式在重载运算符中比较枚举变量?
【问题讨论】:
-
您可能想要
bool operator<(const wahl &wahl1, const wahl &wahl2)或bool operator<(wahl wahl1, wahl wahl2)。 -
您在尝试比较左值时是否使用了左值?也许您的运营商不应该参考。
-
顺便说一句,小心,因为您的操作员不遵守严格的顺序,因此您不应该在某些地方使用它(如
std::sort(wahls.begin(), wahls.end())或std::map<wahl, T>)。 -
你的例子doesn't even compile。
-
@JonathanMee 提示:schere, stein, papier 翻译成剪刀、石头、纸。
标签: c++ enums operator-overloading