c++中关联的表示

  • 本文关键字:表示 关联 c++ c++
  • 更新时间 :
  • 英文 :


我想用c++来表示UML类型的关联。不幸的是,我在

处得到错误
AssociationsP = new Player[n];

即:"没有匹配的函数调用'Player::Player()'。我错过了什么?这个概念是否可行?

class Player;
class Team;
class Player {
private:
    int n;
    Team * AssociationsT;
public:
    Player(int x) : n(x) {
        AssociationsT = new Team[n];
    }
    void setTeam(Team * t) {
        for(int i = 0; i < n; i++) {
            AssociationsT[i] = t[i];
        }
    }
};
class Team {
private:
    int n;
    Player * AssociationsP;
public:
    Team(int x) : n(x) {
        AssociationsP = new Player[n];
    }
    void setPlayer(Player * p) {
        for(int i = 0; i < n; i++) {
            AssociationsP[i] = p[i];
        }
    }
};

看起来您可能需要以下内容:

#include <string>
#include <vector>
class Team;
class Player {
    const std::string name_;
    std::vector<const Team*> AssociationsT;
public:
    Player(const std::string& name) : name_(name) { }
    void setTeam(const Team& t) {
        AssociationsT.push_back(&t);
    }
};
class Team {
    const std::string name_;
    std::vector<const Player*> AssociationsP;
public:
    Team(const std::string& name) : name_(name) { }
    void setPlayer(const Player& p) {
        AssociationsP.push_back(&p);
    }
};
void assignPlayerToTeam(Player& player, Team& team)
{
    team.setPlayer(player);
    player.setTeam(team);
}
int main()
{
    Player bill("Bill");
    Team cubs("Cubs");
    assignPlayerToTeam(bill, cubs);
}