正在将链表添加到构造函数

Adding linked list to constructor

本文关键字:构造函数 添加 链表      更新时间:2023-10-16

I;我真的不知道该怎么称呼我遇到的问题,但它已经困扰了我半个小时,现在我正试图解决它。我正试图将Item类作为清单传递到播放器类中的链接列表中,但我在这样做时遇到了困难。player.cpp没有;无法识别Item类并将其称为"class DLinkedList<>"。我也不确定是否将linkedlist添加到构造函数本身。

#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();
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()
{
}
  • 你的玩家类成员应该(可能)是私人的

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

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