首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >向库存类添加*owner属性

向库存类添加*owner属性
EN

Stack Overflow用户
提问于 2022-06-07 15:24:17
回答 1查看 49关注 0票数 -1

我被一个问题困住了,这个问题可能很基本,而且可能有点过于面向对象。其想法是给“库存”类的每一个对象一个指向类"person“在运行时存在的对象的属性,否则它将指向一个nullptr或类似的东西;这样,每个”库存“都可能被链接到一个特定的"Person”。

它给了我一个声明错误,我找不到另一种方法来实现它。给它一个缺省值为nullptr,不会影响任何事情。

完整项目在这里:https://github.com/Gisbert12843/TextAdventure,我应该在这里添加项目的每一行代码吗?其馀部分与问题/类完全无关,而且工作完美。

代码语言:javascript
复制
#pragma once
#include <iostream>
#include <vector>
#include <sstream>
#include "Object.h"
#include <string>
#include <unordered_map>
#include "Person.h"

class Object;
class Inventory {                                           //High_Level summary of Inventory Items
private:
    string name ="";                                    //Name of the inventory
    std::unordered_map<int, Object *> inventory_map;        //The Inventory based on a hashmap of Pointers to Objects of the 'Object-Class'
    int max_size;                                           //Maximum Size of this inventory
    int current_size = 0;                                       //Current amount of Objects stored in this Inventory
    //Person *owner = nullptr;
    Person *owner;

public:
    
    Inventory(string p_name,int p_max_size, Person *p_owner) { name = p_name, max_size = p_max_size, owner = p_owner; }
    bool addNewItemToInventory(Object* p_addedObject);
    bool removeItemFromInventory(Object* p_removedObject);
    bool hasItem(Object* p_searchedObject);
};

代码语言:javascript
复制
#pragma once
#include <string>
#include <iostream>
#include "date.h"
#include <ctime>
#include <vector>

#include "Object.h"
#include "Inventory.h"

using std::string; using std::vector;



class Person {
private:
    string name;
    char gender;
    date birthdate;
    int age;
    double height;


public:
    Person (string pName, char pGender, double pHeight, string pBirthdate)
    {
        name = pName;
        gender = pGender;
        birthdate = getDateAsDateObj (pBirthdate);
        height = pHeight;
    }

    string getName () { return name; }
    char getGender () { return gender; }
    string getBirthdate () { return getDateAsString (birthdate); }
    double getHeight () { return height; }
    //void takeObject(Object pObjToBeTaken) { ; }

    int getCurrentAge(date pBirthDate, date pCurrentDate = getCurrentDate());
};
EN

回答 1

Stack Overflow用户

发布于 2022-06-07 15:44:53

正如一项建议所建议的那样,正如我以前实际使用的那样,这个解决方案被称为向前声明。

您只需通过添加

代码语言:javascript
复制
class Person;

在盘存课上。

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/72533830

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档