首页 > 解决方案 > C ++:将对象作为参数传递

问题描述

我只是想知道为什么这段代码不能编译:

#include <iostream>

class Player
{
    public:
        Player()
        {

        }
};

class Game
{
    public:
        Game()
        {

        }

        void getPlayer(Player &player)
        {

        }
};

int main()
{
    Game *game = new Game();
    Player *player = new Player();

    game->getPlayer(&player);

    return 0;
}

我想将玩家对象作为参数传递给 Game 类的 getPlayer() 方法。

问候

标签: c++classobject

解决方案


你的方法:

void getPlayer(Player &player)

接受对类型对象的左值引用,Player但您试图将其传递Player **给它,以修复编译错误,只需取消引用您的指针:

game->getPlayer(*player);

但是您的程序设计看起来不正确(将引用传递给调用的方法getPlayer等)


推荐阅读