无法将参数 1 从 'Player *' 转换为 'Player' C++

cannot convert parameter 1 from 'Player *' to 'Player' c++

本文关键字:Player 转换 C++ 参数      更新时间:2023-10-16

首先,我是c++的新手,我试着四处寻找这个,没有运气。

我正在做一个石头剪子布游戏作为c++作业。在我的主要我想实例化我的对象/类这是我的Main.cpp

#include "Player.h"
#include "Match.h"
#include "ComputerAI.h"
Player* player;
ComputerAI* ai;
Match* match;
int main()
{
    player = new Player();
    ai = new ComputerAI();
    match = new Match(player, ai);
    match->StartMatch();
    while(true)
    {
        match->StartNewRound();
    }
    return 0;
}
我得到的错误是在Match(player, ai)
Error 2 error C2664: 'Match::Match(Player,Player)' : cannot convert parameter 1 from 'Player *' to 'Player' 

Match的重载构造函数如下所示:

Match(Player player1, Player player2);

我想我知道错误是什么,因为它基本上说我不能从指针转换为非指针,但我不知道如何解决它。

如果我将构造函数更改为:

Match(Player* player1, Player* player2);

它是快乐的,但这只会给我带来100个新问题。

希望你们能帮帮我。

如果你需要,我可以链接完整的类,但我不确定你是否需要它

看起来,这里并不需要指针。试试这个:

#include "Player.h"
#include "Match.h"
#include "ComputerAI.h"
int main(int argc, char * argv[])
{
    // Avoid global variables. Move them
    // as local main variables.
    Player player;
    ComputerAI ai;
    Match match;
    match.StartMatch();
    while(true)
    {
        match.StartNewRound();
    }
    return 0;
}

考虑到,如果您接受Player作为Match构造函数的参数,您将获得传递实例的副本而不是原件,我猜,这不是您想要的。试一试:

class Match
{
private:
    Player & first;
    Player & second;
public:
    Match(Player & newFirst, Player & newSecond)
        : first(newFirst), second(newSecond)
    {
        // ...
    }
};

你可以写

match = new Match( *player, ai );

或者如果构造函数的第二个形参也不是指针,则

match = new Match( *player, *ai );

虽然在你的代码中ai没有类型Player *.

ai = new ComputerAI();

但是我在你的代码中没有看到动态分配玩家的感觉。

我不能评论,因为我还没有足够的声誉?但是如果你使用match构造函数会给你什么错误呢?

Match(Player* player1, Player* player2)

?

我有一个怀疑,但请记住,当它是一个指针调用该类的函数时,您需要使用->操作符。例如,player1->makeMove();