将链表添加到构造函数

时间:2013-08-11 20:13:24

标签: c++ header

我;我真的不确定该怎么称呼这个问题,但是现在试图解决它已经困扰了我半小时。我正在尝试将一个Item类作为库存传递给播放器类中的链接列表,但是我很难这样做。 player.cpp不识别Item类并将其称为“class DLinkedList<>”。我也不确定将链表添加到构造函数本身。

#include "player.h"
#include "Item.h"
#include "DLinkedList.h"

// ----------------------------------------------------------------
//  Name:           Constructor
//  Description:    Constructor
//  Arguments:      
//  Return Value:   None.
// ----------------------------------------------------------------

player::player(){
    this ->name = "default";
    this ->lvl = 99;
    this ->exp = 99;
    this ->maxweight = 99;
    this ->currentweight = 99;
    this ->health = 99;
    this ->strenght = 99;
    this ->defence = 99;
    this -> //trying to add linked list here
}

player::player( string name, int level, int experience, double maxweight, double   currentweight, int health, int strenght, int defence, DLinkedList<Item> inventory){
    this ->name = name;
    this ->lvl = lvl;
    this ->exp = exp;
    this ->maxweight = maxweight;
    this ->currentweight = currentweight;
    this ->health = health;
    this ->strenght = strenght;
    this ->defence = defence;       
}

这是播放器标题

class player{
public:

//Data members
string name;
int lvl;
int exp;    
double maxweight;
double currentweight;
int health;
int strenght;
int defence;
DLinkedList<Item> inventory;

//Constructor
player();
player(string name, int level, int experience, double maxweight, double currentweight, int health, int strenght, int defence, DLinkedList<Item> inventory);
~player();

2 个答案:

答案 0 :(得分:0)

this -> //trying to add linked list here

应该是:

this ->inventory(); //trying to add linked list here

注意事项:

  • 您在成员面前不需要this->

  • 如果您使用初始化程序列表,您的代码会更好(更小,更高效)

示例:

player::player():
     name("default"),
     lvl(99),
     // and so on
     inventory()
{
}
  • 您的玩家类的成员应该(可能)是私有的

答案 1 :(得分:0)

假设DLinkedList有一个没有构造空链表的参数的构造函数,你不需要做任何事情。编译器将添加对该对象的默认构造函数的调用。

您需要player::player( string name, int level, int experience, double maxweight, double currentweight, int health, int strenght, int defence, DLinkedList<Item> inventory)构造函数中的副本或赋值构造函数。