在这个简单的例子中,如何通过引用传递枚举?

时间:2014-03-06 22:54:34

标签: c++ enums

我的代码存在问题,我修改了这个简单的例子来说明它。

我有一个具有公共枚举PlayerType的Player类。我有一个带有createPlayer方法的Manager类,该方法接受对玩家和玩家类型的引用。

但我无法让它编译 - 注意,我无法更改createPlayer方法的签名,每个param必须是一个对象引用。

我做错了什么?

Player.h

#ifndef PLAYER_H
#define PLAYER_H

using namespace std;

class Player {
  public:
    Player();
    enum PlayerType { FORWARD, DEFENSEMAN, GOALIE };
    void setType(PlayerType);
  private:
    PlayerType type;
};

#endif

Player.cc

#include <iostream>

using namespace std;

#include "Player.h"

Player::Player() {
}

void Player::setType(PlayerType type) {
  this->type = type;
}

Manager.h

#ifndef MANAGER_H
#define MANAGER_H

using namespace std;

#include "Player.h"

class Manager {
  public:
    void createPlayer(Player& player, PlayerType& playerType);
};

#endif

Manager.cc

#include <iostream>

using namespace std;

#include "Player.h"

#include "Manager.h"

void Manager::createPlayer(Player& player, PlayerType& playerType) {
  cout << "inside Manager::createPlayer" << endl;
}

Main.cc

#include <iostream>

using namespace std;

#include "Player.h"
#include "Manager.h"

int main() {

  Manager manager;
  Player player;
  manager.createPlayer(player, Player::FORWARD);

  return 0;
}

当我编译gcc -o a.out *.cc *.h时,我收到此错误:

In file included from Main.cc:6:0:
Manager.h:10:39: error: ‘PlayerType’ has not been declared
Main.cc: In function ‘int main()’:
Main.cc:12:47: error: no matching function for call to ‘Manager::createPlayer(Player&, Player::PlayerType)’
Main.cc:12:47: note: candidate is:
Manager.h:10:10: note: void Manager::createPlayer(Player&, int&)
Manager.h:10:10: note:   no known conversion for argument 2 from ‘Player::PlayerType’ to ‘int&’
In file included from Manager.cc:7:0:
Manager.h:10:39: error: ‘PlayerType’ has not been declared
Manager.cc:9:44: error: ‘PlayerType’ has not been declared
Manager.h:10:39: error: ‘PlayerType’ has not been declared

我该怎么做才能使这项工作?

3 个答案:

答案 0 :(得分:2)

能够使用您需要的引用将值存储到变量中。

int main() {

  Manager manager;
  Player player;
  Player::PlayerType t = Player::FORWARD;
  manager.createPlayer(player,t);

  return 0;
}

答案 1 :(得分:1)

您需要更改

void createPlayer(Player& player, Player::PlayerType& playerType);

void createPlayer(Player& player, const Player::PlayerType& playerType);

将Player :: FORWARD作为参数传递会创建一个临时的PlayerType值,该值只能作为const引用或值传递。

答案 2 :(得分:1)

问题在于此次通话

manager.createPlayer(player, Player::FORWARD);

第二个参数是临时对象,您不能将非const引用与临时对象绑定。

所以你应该将函数声明为

void Manager::createPlayer(Player& player, const Player::PlayerType& playerType)

虽然我没有看到使用该引用的很大意义。我会声明函数更简单

void Manager::createPlayer(Player& player, Player::PlayerType playerType)

参考。