【发布时间】:2018-07-05 05:21:03
【问题描述】:
我对如何正确构造 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。我忽略了一些错误吗?
【问题讨论】:
-
PlayerStats stats();是一个函数声明。它声明了一个名为stats的函数,该函数返回一个PlayerStats并且没有参数。见most vexing parse。 -
您不需要所有代码来显示问题。发布的大多数代码都是无关紧要的。你应该瞄准minimal reproducible example。
-
@TreytenCarey 不。正如我所说,大部分代码都是无关紧要的。那不是minimal reproducible example。
-
MCVE 的美妙之处在于,当您接近一个时,您的代码会更少。更少的代码意味着可以隐藏错误的表面积更小。最终,剩下的代码太少了,无法隐藏该错误并暴露了该错误。通常你会得到大约 3/4 的 MCVE,抱怨并修复错误,但有时你可以完全隔离傻瓜仍然不知道如何解决它。即使新手 C++ 程序员进入 MCVE
#include <iostream> class PlayerStats { PlayerStats(){cout << "Hello!"; } }; int main() { PlayerStats stats(); },他们仍然需要帮助 -
@TreytenCarey minimal reproducible example 的部分意义在于隔离问题。它需要一些努力,但它很容易制作。这是值得鼓励的事情之一,甚至是这里的预期。我什至不必查看 OP 的代码,我可以立即发现问题。但这并不能帮助 OP 成为更好的程序员。生成minimal reproducible example 确实如此。