Warning: file_get_contents(/data/phpspider/zhask/data//catemap/6/cplusplus/129.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C++ 如何访问从文件输出创建的obect实例?_C++_File Io_Instantiation_Function Calls_Member Functions - Fatal编程技术网

C++ 如何访问从文件输出创建的obect实例?

C++ 如何访问从文件输出创建的obect实例?,c++,file-io,instantiation,function-calls,member-functions,C++,File Io,Instantiation,Function Calls,Member Functions,我在使用文件I/O为正在开发的游戏创建类实例时遇到问题。这可能是一个愚蠢的问题,但我无法理解为什么编译器似乎成功地从文本文件中存储的数据创建了对象,而我却无法访问它们。(我取出.display()函数调用来测试这一点,并添加了一个简单的cout您没有发送任何您收到的信息来创建新对象。添加一个构造函数,该构造函数接收带有信息的字符串,然后初始化属性,如下所示: Atrributes::Attributes(String data){ //parse string and initialize

我在使用文件I/O为正在开发的游戏创建类实例时遇到问题。这可能是一个愚蠢的问题,但我无法理解为什么编译器似乎成功地从文本文件中存储的数据创建了对象,而我却无法访问它们。(我取出.display()函数调用来测试这一点,并添加了一个简单的cout您没有发送任何您收到的信息来创建新对象。添加一个构造函数,该构造函数接收带有信息的字符串,然后初始化
属性,如下所示:

Atrributes::Attributes(String data){
  //parse string and initialize data here
}

另外,我建议不要让你的
属性
对象与保存数据的变量同名。即使它是无害的(我也不确定它是否无害)C++中,所有的变量都需要在代码中用名称来声明。在你的循环中,你声明了一组指针变量,这些变量都被命名为“代码>行<代码>,然后尝试使用其他命名变量,如代码<健康> /代码>,<代码>疲劳>代码>等。 我不认为可以直接从这样的文件中按名称创建变量,但是可以读取文件并创建包含文件中数据的对象数组或向量
属性
构造函数中,然后将创建的指针存储在数组或映射中,您可以稍后访问这些数组或映射来调用方法,如
display()
。如果您确实希望在代码中有一个名为
health
的变量,则必须在代码中的某个位置声明它

另一个次要问题是,您正在循环作用域中重用变量名
(之前声明为std::string)。这可能会起作用,但会造成混淆,应该避免。请调用指针变量,例如
attItem

例如:

Attributes * attItem = new Attributes(line);
attList.push_back(attItem);

C和C++不允许在运行时创建新的变量名。因此<代码> Health在Health.DePosid()中,不能来自读取文件。

您可以做的是拥有一个
属性的集合
(例如
attList
)和一个为您找到合适属性的函数:

Attribute health = attList.find("health"); 
(或者,如果您喜欢使用
地图
,您可以执行以下操作:

Attribute health = attList["health"]; 
当然,另一种方法是在每个对象中存储属性,例如

class PlayerBase
{
  private:
    Attribute health;
    Attribute speed;
    ...
  public:
    void SetAttribute(const string& name, const Attribute& attr);
}; 
然后通过比较
string name
,可以找到正确的属性:

void SetAttribute(const string& name, const Attribute& attr)
{
   if (name == "health") health = attr;
   if (name == "speed") speed = attr;
   ...
}

很抱歉,我应该更进一步地介绍我的细节…我已经为类添加了头文件,我只是想测试我是否可以通过使用数据文件创建对象来创建更干净的代码,如果这样做有意义的话?可能吗?你的意思是,在程序运行之前创建对象?基本上……是的,我想!所以r据我所知,这是不可能的。如果您有权访问数据库,您可以保存有关对象的所有信息,但在程序重新启动时,您仍然必须使用对象的所有信息重新初始化该对象。您的代码非常干净(减去变量命名),我唯一建议的另一件事是将所有数据读取移到另一个函数中,以保持main干净。
Attribute health = attList["health"]; 
class PlayerBase
{
  private:
    Attribute health;
    Attribute speed;
    ...
  public:
    void SetAttribute(const string& name, const Attribute& attr);
}; 
void SetAttribute(const string& name, const Attribute& attr)
{
   if (name == "health") health = attr;
   if (name == "speed") speed = attr;
   ...
}