问题描述
我一直在试图理解在这段代码中重载的操作符的使用,但是,我不能围绕它。我不完全明白重载运算符的目的或为什么它需要。我知道这是一个新手问题,但如果有人可以解释它,我会非常感谢。
I have been trying to understand the use of the overloaded operator in this code, however, I cannot wrap my mind around it. I do not understand exactly the purpose of the overloaded operator or why it is needed. I know that this is a newbie question but if someone could explain it I would greatly appreciate it.
const int Card::operator+(const Card& B)
{
if ((faceValue ==1 || B.faceValue == 1) && (faceValue + B.faceValue)<= 11)
return 10 + faceValue + (B.faceValue);
else
return faceValue + (B.faceValue);
}
再次感谢您的帮助。
推荐答案
目的是将两个 Card
对象添加到一起。通常,只能使用 +
在C和C ++中添加整数类型,指针类型[带整数类型]和浮点类型。其他任何东西都需要一个特殊的操作符。
The "purpose" is to add two Card
objects together. Typically, you can only use +
to add integer types, pointer types [with an integer type] and float types in C and C++. Anything else will need a special operator.
其中的实际数学似乎是BlackJack的一部分,其中 ACE
被计为 1
或 10
。
The actual math inside it appears to be some part of BlackJack, where an ACE
is counted as either 1
or 10
depending on circumstances.
编辑:我个人认为这不是很好地使用运算符+
,因为 operator +
是将两个东西加在一起,不应用逻辑,然后根据一些游戏规则做不同的添加。这遵循没有预言的规则。应使用具有合理名称的函数,如 CalculateHand
。
I personally don't think this is good use of the operator+
, since the expectation of operator+
is to add two things together, not apply logic and then do different additions based on some "rules of a game". This follows the rule of "no suprises". A function with a sensible name such as CalculateHand
should be used instead.
编辑2:除了上述思考之外,我还补充说,一个纸牌游戏的逻辑不应该在卡
。游戏的逻辑属于任何处理卡 - 卡应该表现完全相同,不管是什么游戏,扑克,BlackJack或接龙。
Further to the above "thinking", I would add that the logic of, say, a card-game should not be dealt with in the Card
. The logic of the game belongs in whatever "handles" the cards - cards should behave exactly the same no matter what the game is, Poker, BlackJack or Solitaire.
这篇关于重载运算符,在此示例中,覆盖运算符的用途是什么的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!