overloading operators, what is the purpose of the overladed operator in this example

南楼画角 提交于 2019-12-11 18:40:06

问题


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);

}

Again I really appreciate any help on this.


回答1:


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.

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.

Edit: 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.

Edit2: 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.




回答2:


It is IMHO a good example of when you should not use operator overloading. It seems the code returns a value calculated according to the rules of a specific game. Maybe BlackJack, but it doesn't matter. I think in this case it should better be a function with an appropriate name instead of an overloaded operator + as the latter has no general concept with cards.




回答3:


Operator overloading comes into picture whenever you are operating on user defined types for eg: here objects of class Card. '+' operator is meant to be used for primitive data types like int, float, double. So what you are doing here is adding to the functionality of '+' to operate upon class objects.

Also @Mats Petersson mentioned is correct, you should not impose any logic in operator overloaded function, instead use different function if required.



来源:https://stackoverflow.com/questions/16505267/overloading-operators-what-is-the-purpose-of-the-overladed-operator-in-this-exa

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!