如何正确构造C ++对象?

时间:2018-01-25 20:50:47

标签: c++ c++11

我对如何正确构建c ++对象感到困惑。

我有这堂课:

////////////////////////
// "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;
}

当我在main(),

中构造它时
int main()
{

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

    return 0;
}

我的预期结果是1000 0-0-0,但是当我尝试调用其他构造函数时,

int main()
{

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

    return 0;
}

我刚刚打印出整数1,我怀疑它是垃圾值。我忽略了一些错误?

2 个答案:

答案 0 :(得分:11)

PlayerStats stats()声明一个名为stats的函数,该函数返回PlayerStats并且不带参数。这是所谓的“most vexing parse”的实例;基本上,只要编译器 将语句解释为函数声明,那么必须这样做。理解混乱。

要解决此问题,请使用:

PlayerStats stats;

或:

PlayerStats stats{};

答案 1 :(得分:3)

 PlayerStats stats();

声明一个函数。要调用默认构造函数,请使用

 PlayerStats stats;

这称为most vexing parse