我有一个看起来像这样的类(class):
class Player
{
friend bool operator>=(Player &pl1, Player &pl2)
{
return true;
};
private:
int nr, height, weight;
}
球员有数量、高度和体重。
现在我想知道 Player1 是否比 Player2 更大和/或更重。在此之后,我想像这样打印出来:
Player A is 2 cm bigger (smaller) and 7 kg heavier (lighter) than Player B.
当我只能返回 true 或 false 时,我该如何管理它?我可以在他更大更重时返回 true 或者当他更小更轻时返回 false,但是我应该如何管理更大/更轻的 |更小/更重的情况?
编辑:我必须用
operator>=
来做。这是我学校的考试,条件是这样。下面是正文:最佳答案
因此,如果您以不同的方式组织类(class),也许您可以执行以下操作:
class PlayerWeight {
private:
int weight;
public:
int getWeight() const {
return weight;
}
bool operator >=( const PlayerWeight &playerWeight ) {
return weight >= playerWeight.getWeight();
}
PlayerWeight( int weight ) : weight( weight ) {
}
};
class PlayerHeight {
private:
int height;
public:
int getHeight() const {
return height;
}
bool operator >=( const PlayerHeight &playerHeight ) {
return height >= playerHeight.getHeight();
}
PlayerHeight( int height ) : height( height ) {
}
};
class Player : public PlayerHeight, public PlayerWeight {
public:
PlayerHeight& height() {
return *this;
}
PlayerWeight& weight() {
return *this;
}
Player( int height, int weight ) : PlayerHeight( height ), PlayerWeight( weight ) {
}
};
int main( int argc, char**argv ) {
Player playerA( 72, 180 ), playerB( 74, 160 );
// comparison
std::cout << "Player A is " << ( (PlayerHeight)playerA >= playerB ? "bigger" : "smaller" ) << " and " << ( (PlayerWeight)playerA >= playerB ? "heavier" : "lighter" ) << std::endl;
// or...
std::cout << "Player A is " << ( playerA.height() >= playerB ? "bigger" : "smaller" ) << " and " << ( playerA.weight() >= playerB ? "heavier" : "lighter" ) << std::endl;
return 0;
}
关于C++ 运算符重载 >= 具有 2 个不同的返回,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/30868616/