运算符重载 +班级成员的标志
我有一个问题,我需要使用运算符重载添加两个类成员。问题还在于我需要添加的成员是字符串..我尝试使用 stringstream 但我似乎没有工作,发生了无限循环的错误。有没有一种非常简单的方法可以将字符串转换为整数进行相加?或者至少有一种将两个字符串相加并打印出总和的方法
class PlayingCard
{
public:
char suit;
string rank;
PlayingCard operator +();
};
PlayingCard deck[52];
PlayingCard player[10];
PlayingCard dealer[10];
int playerHits = 2;
int dealerHits = 2;
PlayingCard PlayingCard::operator+()
{
int r1;
int r2;
stringstream pr1;
stringstream pr2;
string temp1 = player[1].rank;
string temp2 = player[2].rank;
pr1 << temp1;
pr2 << temp2;
pr1 >> r1;
pr2 >> r2;
return(r1 + r2);
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
您的
operator+
不带任何参数,因此无法工作。成员
operator+
必须具有以下签名:自由
operator+
需要看起来像这样:嗯,这是一种方法。
我建议你回到书本;)
Your
operator+
does not take any parameters and therefore cannot work.A member
operator+
has to have the following signature:A free
operator+
needs to look that way:Well, that is one way to go.
I suggest you get back to the books ;)
您可能想首先定义“将两张扑克牌相加”操作的含义。假设我手上有黑桃 J 和红心 Q。作为物理实体,这些不会相加。
然而,他们的等级确实如此;我们可以说
jack + queen => 11 + 12 => 23
如果我们为它们的排名分配整数值。显然不存在“23张牌”。因此,将两个PlayingCard
添加在一起无法可靠地返回有效的PlayingCard
。问题是,在需要时查询他们的排名是否会更容易?例如:
在这种情况下,甚至没有返回中间
PlayingCard
——我们关心的只是rank
的总和>卡1和卡2
。抱歉,我有点偏离了您的来源...上面假设您将排名存储为
int
,就像您在 上一个问题。这种方法非常可取,因为您将对其进行数学运算(就像上面我的愚蠢示例)。You might want to first define what you mean by the operation of "adding two playing cards together." Let's say I have the jack of spades and the queen of hearts, physically in my hand. As physical entities, those don't add.
Their rank, however does; we could say
jack + queen => 11 + 12 => 23
if we assign integer values to their ranks. Obviously there is no "23 card". Therefore, adding twoPlayingCard
s together can not reliably return a validPlayingCard
.The question is, would it just be easier to query their
rank
when it is needed? For example:In this case, there isn't even a for an intermediate
PlayingCard
to be returned -- all we care about is the sum of therank
s ofcard1
andcard2
.Sorry, I've deviated from your source a bit...the above is assuming you would store the rank as an
int
, as you had in your previous question. This method is highly preferable since you will be doing mathematical operations on them (like my dumb example above).只使用
atoi
怎么样?How about just using
atoi
?这里您将返回类型定义为 PlayingCard
但这里您返回一个整数:
Here you define the return type as PlayingCard
But here you return an integer: