0

我不确定为什么会出现错误,因为我在另一个运行良好的程序中有非常相似的代码。这是我第一次在这个论坛上发帖,所以我不确定要包括什么,但这里是我收到错误的代码。

int AddPlayers(vector<Player>& players)
{
    string name;
    double wins;
    double losses;
    double draws;
    int x = 0;
    Player findPlayer("null", 0, 0, 0);
    cout << "Name of player you would like to add?" << endl;
    cin >> name;
    for (x = 0; x < players.size(); x++ )
    {
        findPlayer = players[x];
        findPlayer.getName();
        x++;
        if (name == findPlayer.getName())
        {
            cout << "That player is already in the tournament." << endl;
            return 1;
        }
        Player newPlayer = (name, wins, losses, draws);
        players.push_back(newPlayer);
    } 
}
4

3 回答 3

3
Player newPlayer = (name, wins, losses, draws);

这是错误的语法。您正在目睹逗号运算符的实际作用,它实际上是newPlayer使用draws. 由于draws是 a double,因此初始化会给您该错误。

看来您想要:

Player newPlayer(name, wins, losses, draws);
于 2013-03-28T18:00:59.770 回答
1
Player newPlayer = (name, wins, losses, draws);

去掉括号后,你剩下

Player newPlayer = name, wins, losses, draws;

现在这是逗号运算符:它计算其操作数并返回最后一个,draw在这种情况下。draw是 a double,显然没有构造函数Player需要 a double,因此出现错误。无论如何,您想从四个变量中构造一个对象:

Player newPlayer(name, wins, losses, draws);
于 2013-03-28T18:03:30.783 回答
1

该指令:

Player newPlayer = (name, wins, losses, draws);

尝试Player从表达式复制初始化对象(name, wins, losses, draws)。由于逗号运算符的语义,前三个子表达式的值被丢弃,只有最后一个子表达式决定表达式的值(和类型)。

因此,表达式:

(name, wins, losses, draws)

等价于表达式:

 (draws)

由于drawshas type double,这实际上是尝试复制初始化Player具有 a的类型的对象double。由于Player显然没有构造函数采用 a double,因此编译器会生成错误。

你很可能不想在那里写一个表达式,而是一个构造函数的参数列表Player

 Player newPlayer(name, wins, losses, draws);
于 2013-03-28T18:03:44.860 回答