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

How can I access obect instances created from file output?

本文关键字:创建 输出 obect 实例 文件 何访问 访问      更新时间:2023-10-16

我在使用文件I/O为我正在开发的游戏创建类的实例时遇到了问题。这可能是一个愚蠢的问题,但我无法理解为什么编译器似乎成功地从存储在文本文件中的数据创建了对象,而我却无法访问它们。(我去掉了.display()函数调用来测试这一点,并添加了一个简单的cout<lt;"对象已创建";到构造函数中,以检查是否已创建某些内容。)

但是试图访问单个对象的代码给了我错误:当试图访问对象成员函数时,"标识符"是未定义的。我可能做了一些完全错误的事情,如果能朝着正确的方向努力,我会很感激。我已经尝试在while循环中更改语法来创建对象,但我还没有破解它。提前谢谢!下面的代码。。。

main.cpp

#include <iostream>
#include <string>
#include <fstream>
#include "Attributes.h"
using std::cout;
using std::endl;
using std::cin;
using std::ofstream;
using std::ifstream;
using std::getline;
using std::cerr;

int main() {
    std::string line;
    ifstream attdata;
    attdata.open("data.txt");
    if (attdata.is_open())
    {
        while (attdata.good())
        {
            getline (attdata, line);
            Attributes * line = new Attributes;
        }
        attdata.close();
    }
    else cerr << "Unable to open file.";
health.display();
fatigue.display();
attack.display();
skill.display();
defence.display();
skilldef.display();
speed.display();
luck.display();
};

data.txt

health
fatigue
attack
skill
defence
skilldef
speed
luck

Atributes.h

#pragma once
#include <string>
class Attributes
{
public:
    Attributes(void);
    Attributes(std::string name, std::string shortName, std::string desc, int min, int max);
    ~Attributes(void);
    void display();
private:
    std::string m_nameLong;
    std::string m_nameShort;
    std::string m_desc;
    int m_minValue;
    int m_maxValue;
};

在C++中,所有变量都需要在代码中按名称声明。您在循环中声明了一组指针变量,全部命名为line,然后尝试使用其他尚未创建的命名变量,如healthfatigue等。

我不认为你可以直接从这样的文件中按名称创建变量,但你可以读取文件并创建一个包含文件数据的对象数组或向量。您可以将getline()读取的字符串传递到Attributes构造函数中,然后将创建的指针存储在数组或映射中,您可以稍后访问这些数组或映射来调用display()等方法。如果您真的想在代码中使用一个名为health的变量,则必须在代码中的某个地方声明它。

另一个次要点是,您正在循环范围中重用变量名line(您之前声明为std::string)。这可能有效,但令人困惑,应该避免。用其他方法调用指针变量,比如attItem

例如:

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

您不会发送为创建新对象而收到的任何信息。添加一个构造函数,该构造函数接收包含信息的字符串,然后初始化Attributes,如下所示:

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

此外,我建议不要使Attributes对象与保存数据的变量具有相同的名称。即使它是无害的(我不确定它是不是),它也不是很干净。

C和C++不允许在运行时创建新的变量名称。因此CCD_ 13中的CCD_。

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

Attribute health = attList.find("health"); 

(或者,如果你更喜欢使用map,你可以这样做:

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;
   ...
}