使用C ++中函数的返回值初始化类

时间:2018-12-09 12:06:30

标签: c++ class

我必须上课,我想用第二个类的函数的返回值初始化第一类。为了澄清,考虑一下

class Bet
{
private:
  unsigned int money;
  char result; // one of o, e, 1, 2, 3, 4, 5, 6
public:
  Bet(unsigned int m = 0, char r = '0') : money{m}, result{r} {}
  unsigned int getMoney() const { return money; }
  char getResult() const { return result; }
};

class Player
{
protected:
  string name;
  unsigned int  money;
  double betMoney;
  char result;

public:
  Player(string _name="NONE", unsigned int  _money=0)
     :name{_name}, money{_money} {}
  ~Player();
  double getMoney() const {return money;}  
  string getName() {return name;}
  virtual tuple<unsigned int, char> bet();
  virtual void win(double winMoney);
};

class HumanPlayer : public Player
{
public:
  HumanPlayer(string _name, unsigned int _money = 1000):Player(_name,_money) {}
  void win(double winMoney) override
  {
    money = money + result + winMoney;
  }

  tuple<unsigned int, char> bet() override
  {
    cout << "Player" << name << ", your bet:" 
     << "amount of money (you have " << money << "):" << endl;
    cin >> betMoney;
    while (betMoney > money)
    {
      cout << "Player" << name << " only has " << money << " Euros):" << endl;
      cin >> betMoney;
    }
    money-=betMoney;
    cout << "result (o[dd], e[ven], 1, 2, 3, 4, 5, 6):";
    cin >> result;
    return {money,result};
  }
};

我想用HumanPlayer类的下注函数初始化Class Bet

 Player* p = new Player{"John,1000);  // p is a pointer to an object of Player class      
 Bet b{p->bet()};

首先使用指针初始化类播放器,然后调用用于初始化类Bet的下注函数。我使用了元组,但是没有用。我不能更改Bet类,但应该修改Player,HumanPlayer和ComputerPlayer类。

1 个答案:

答案 0 :(得分:0)

更改返回类型bet

Player中:

virtual ~Player() {}

virtual Bet bet() = 0;

HumanPlayer中:

Bet bet() override
{
    cout << "Player" << name << ", your bet:" 
     << "amount of money (you have " << money << "):" << endl;
    cin >> betMoney;
    while (betMoney > money)
    {
      cout << "Player" << name << " only has " << money << " Euros):" << endl;
      cin >> betMoney;
    }
    money-=betMoney;
    cout << "result (o[dd], e[ven], 1, 2, 3, 4, 5, 6):";
    cin >> result;
    return Bet {money,result};
}