我是C ++的新手并试图制作一个二十一点模拟器。玩家是一个存储从牌组发出的牌的类; class Card包含套装值和面值。我不断收到错误消息"控件可能会达到非空函数的结束"对于Card Player :: getCard(int index)const,我做错了什么?也有人可以检查我的代码中是否存在任何逻辑缺陷,因为我无法运行它并检查是否有错误消息?
#include "Player.h"
#include "Game.h"
#include "Card.h"
using namespace std;
Player::Player( )
{
// The Player has no Cards in his hand
myNumberOfCards = 0;
}
std::ostream& operator <<( std::ostream& outs, const Player & p )
{
// print out all the actual cards in the array myCards
for (int i = 0; i < p.cardCount(); i++)
{
outs << p.myCards[i] << endl;
}
return( outs );
}
void Player::acceptCard(Card c)
{
// as long as there is space in the array myCards, place Card c into myCards
// if there is not enough space for another card, throw an exception
try
{
for (; myNumberOfCards < MAXCARDS; myNumberOfCards++)
myCards[ myNumberOfCards ] = c;
if (myNumberOfCards > MAXCARDS)
throw myNumberOfCards;
}
catch (int e)
{
std::logic_error( "more than maximum of cards possible" ); // Since the player must be busted if he has more than 11 cards, how should I set the outcome to playerbusted if I have a bool in the game class?
}
}
Card Player::getCard( int index ) const
{
// return the requested card
// if the index is bad, throw an exception
try
{
while ( index > 0 && index < myNumberOfCards )
return ( myCards[ index ] );
if (index < 0 || index > myNumberOfCards)
throw index;
}
catch (int e)
{
std::logic_error( "bad index" ); // why there's an error?
}
}
int Player:: cardCount() const
{
// return the number of cards stored in my array
return myNumberOfCards;
}
int Player::handcount( ) const
{
// total up the points in this player's hand
// Ace's might be worth 1 or 11
Player p;
int total = 0;
bool hasAce = false;
for (int i = 0; i < myNumberOfCards; i++)
{
total += myCards[i].count();
if (myCards[i].getFace() == ACE)
hasAce = true;
}
if (total < 11 && hasAce == true)
total += 10;
return( total );
}
bool Player::hasBlackJack( ) const
{
bool result = false;
if (myNumberOfCards == 2 && handcount() == 21)
{
result = true;
}
return( result );
}
答案 0 :(得分:2)
// vvvv must return a Card
Card Player::getCard( int index ) const
{
try
{
// ...
throw index;
}
catch (int e)
{
std::logic_error( "bad index" ); // this doesn't throw, so will continue past
}
// ends up here, doesn't return
}
你不会抛出一个std::logic_error
,只需构建一个,然后不做任何事情。
如果出现错误throw index
,您最终会触及函数的底部而不返回任何内容,这是Undefined Behaviour(非常糟糕,任何事情都可能发生)。
可能你的意思是throw std::logic_error("bad index");
?这会导致你以异常退出函数,而不是正常返回,因此不会导致问题。
删除try
中的catch
/ getCard
并替换
throw index;
与
throw std::logic_error("bad index");
因为调用者的最终结果是相同的。抛弃while
,因为它不是一个循环,只是一个检查。这是简化版:
Card Player::getCard( int index ) const
{
// return the requested card
// if the index is bad, throw an exception
if ( index > 0 && index < myNumberOfCards )
return ( myCards[ index ] );
else
throw std::logic_error("bad index");
}
您在acceptCard
中犯了同样的错误,但由于它返回void
,因此您没有看到错误消息:&#34;从底部掉落&#34;允许使用void
函数,它的行为就像最后一行只是return;
。
另外,请重新考虑您对不良做法的使用using namespace std;
和endl
。