jeudi 25 janvier 2018

How to proper construct C++ objects?

I am confused about how to correctly construct c++ objects.

I have this class:

////////////////////////
// "PlayerStats.h"
//
// This class is responsible for maintaining each
//   player's stats for a given tournament and simulating
//   how these stats change as the player interacts with
//   other players.
typedef double Elo;
class PlayerStats
{
    double expectedScore(PlayerStats b) const;
    Elo elo;
    int wins;
    int losses;
    int ties;

  public:
    PlayerStats() : elo(1000), wins(0), losses(0), ties(0) {}
    PlayerStats(Elo elo) : elo(elo), wins(0), losses(0), ties(0) {}
    PlayerStats(Elo elo, int wins, int losses, int ties) : elo(elo), wins(wins), losses(losses), ties(ties) {}

    friend std::ostream &operator<<(std::ostream &os, const PlayerStats &ps);
};

// render these stats to the stream in the format:
// <elo (rounded integer)> (<wins>-<losses>-<ties>)
std::ostream &operator<<(std::ostream &os, const PlayerStats &ps)
{
    os << (int) (ps.elo + 0.5);  // round elo and out put it
    os << " " << ps.wins << "-" << ps.losses << "-" << ps.ties;
    return os;
}

When I construct it this way in main(),

int main()
{

    PlayerStats stats(1000);
    std::cout << stats << std::endl;

    return 0;
}

I get my expected result 1000 0-0-0, but when I try to call the other constructor,

int main()
{

    PlayerStats stats();
    std::cout << stats << std::endl;

    return 0;
}

I just get the integer 1 printed out which I suspect is a garbage value. It there some error I'm overlooking?

Aucun commentaire:

Enregistrer un commentaire