如何获得对另一个类的引用,以便从所述类内部获取变量值?

问题描述 投票:-1回答:1

我有一个叫MapGraph的班级,还有另一个叫GameState的班级。我正在从GoToLocation(NextLocation);调用两个函数,分别称为Game->SidePanel();main。 GoToLocation()声明和定义分别存在于MapGraph.hMapGraph.cpp中,而SidePanel()声明和定义分别存在于GameState.hGameState.cpp中。在SidePanel()中,我试图获取一个名为CurrentLocation的变量的值,该变量存在于MapGraph中并且是公共的。我已经将MapGraph.h包含在GameState.cpp中,并且将该类声明为class MapGraph;,但是我不知道如何获取变量的值。如果我执行MapGraph* Map = new MapGraph;,则始终会给我变量的初始值,而不是更新后的值。任何帮助,将不胜感激。谢谢。

main.cpp中的代码:

int main()
{
    MapGraph* Map = new MapGraph;
    GameState* Game = new GameState;
    //Game->MainMenu();

    Map->GoToLocation(MapGraph::LocationNames::CastleSquare);
    Game->SidePanel();

    //system("CLS");
    return 0;
}

MapGraph.h

#pragma once

#include <iostream>
#include <list>
#include <string.h>

class MapGraph
{
public:
    MapGraph();

    enum class LocationNames
    {
        GraveYard = 0,
        Sewers = 1,
        Outskirts = 2,
        Barracks = 3,
        Town = 4,
        CastleSquare = 5,
        ThroneRoom = 6,
        Forest = 7,
        Gutter = 8,
        HunterShack = 9
    };

    std::string LocNamesString[10] =
    {
        "Grave Yard",
        "Sewers",
        "Outskirts",
        "Barracks",
        "Town",
        "Castle Square",
        "Throne Room",
        "Forest",
        "Gutter",
        "Hunter Shack"
    };

    LocationNames CurrentLocation;
    void GoToLocation(LocationNames NextLocation);
};

GameState.cpp

#include <iostream>
#include <stdlib.h>
#include "GameState.h"
#include "MapGraph.h"

class MapGraph;

void GameState::SidePanel()
{
    MapGraph* Map = new MapGraph;

    std::cout << Map->LocNamesString[(int)Map->CurrentLocation];
}

P.S。:我尝试将MapGraph.h中的CurrentLocation更改为static,但始终会生成链接器错误2001。只要删除单词static,该错误就会消失。

谢谢。]

c++ static-variables
1个回答
0
投票

有几种设计这种关系的方法。由您决定哪个最适合您的总体设计。 (一个大问题是您希望同时存在几个MapGraph对象?)最简单的方法可能是将所需的变量作为参数传递。

void GameState::SidePanel(cosnt MapGraph & Map)
{
    std::cout << Map.LocNamesString[(int)Map.CurrentLocation];
}

仍然,我会更进一步,将这一行逻辑合并到MapGraph类中。在这种情况下,您的功能将变为

void GameState::SidePanel(cosnt MapGraph & Map)
{
    std::cout << Map.CurrentLocationName();
}

并且以下内容添加到MapGraph定义中

class MapGraph {
    // Existing stuff here

public:
    std::string CurrentLocationName()
    {
        return LocNamesString[(int)CurrentLocation];
    }

    // Possibly more definitions here
};

作为一般规则,只有您的MapGraph实现应需要知道如何存储MapGraph数据。当其他代码需要MapGraph数据的组合(例如将当前位置转换为字符串)时,MapGraph类应为此提供一个接口。

顺便说一下,LocNamesString可能应该是staticconststatic关键字表示名称字符串在MapGraph对象与MapGraph对象之间没有变化。 const关键字表示在程序执行期间名称字符串未更改。

© www.soinside.com 2019 - 2024. All rights reserved.