2013-08-22 33 views
1

如果之前已询问过此问题,请事先致歉。可从多个文件和函数访问的类值C++

我把我的所有技能与谷歌使用和仍然没有,所以如果这个问题已经回答之前请将链接的答案,我会基本上结束这个问题。

无论如何,所有这一切,我的问题是,我有一个类“Player.hpp”和一个相应的“Player.cpp”,我已经为其定义了“player”的位置系统初始化罚值(这是类的一个函数),但是当玩家转到“play()”函数(该函数保存游戏的骨骼并位于另一个.cpp文件中),当我使用函数来获取我存储在那里的位置没有任何存储...任何帮助,将不胜感激。

如果你不明白我在问什么,请评论,我会详细说明。

下面的代码:

//Player.hpp 
class player 
{ 
public: 
    std::string getLocation(); 
    void setLocation(std::string local); 
    void initLocation(); 

private: 
    std::string location; 
}; 

//Player.cpp 
void player::initLocation() 
{ 
    player::location = "B0"; 
    return; 
} 
std::string player::getLocation() 
{ 
    return player::location; 
} 
void player::setLocation(std::string local) 
{ 
    player::location = local; 
    return; 
} 

//Main.cpp 
//.... 
player plays; 
plays.initLocation(); 
//.... 

//Game.cpp 
//... 
player plays; 
std::string local = plays.getLocation(); //When I check there isn't a value that gets stored... 
if(local.find(...)...) 

同样,任何帮助表示赞赏和我道歉,如果这样的问题已经问。

编辑:

我想我应该澄清,我也想改变,从房间到另一个房间的进行存储为player值(因为这是一个魔域风格的游戏,我做)

+1

您是否真的在'Game.cpp'中创建了'player'的不同实例,而不是您在'Main.cpp'中初始化的'player'实例?如果是这样,那就是你的问题。 – jxh

+1

你如何“检查”“没有存储的值”? –

+0

@jxh我不太清楚如何去做(因为我对编程还很陌生),但我会看看有关查找信息。 @Kerrek SB我从“getLocation()' – Piraxis

回答

1

假设player的每个实例可能位于一个单独的位置,可以通过使用其构造函数中的默认位置初始化player的位置来解决此问题。这消除了对initLocation()的需求,因此不需要从Main.cpp调用它。

//Player.hpp 
class player 
{ 
public: 
    std::string getLocation(); 
    void setLocation(std::string local); 

    player() : location("B0") {} 

private: 
    std::string location; 
}; 
+0

好吧,所以它的工作......它只是让我发现我有一个非常不同的问题,我可以解决...... – Piraxis

0

这看起来好像你在类变量声明的前面省略static

class player 
{ 
    // ... 
    static std::string location; 
}; 

...然后还需要一个定义。当然,定义也成为初始化该值的主要位置:

// Player.cpp 
std:string player::location("B0"); 

使初始化功能变得不必要。

+0

”应该“接收到数据后显示本地值来检查它是否为”静态“,因为我需要能够更改位置的值,所以我可以从任何地方加载它,它仍然是正确的设定值。 – Piraxis