2013-07-19 75 views
0

我无法使用文件I/O为我正在处理的游戏创建类的实例。这可能是一个愚蠢的问题,但我无法理解为什么编译器似乎成功地从存储在文本文件中的数据创建对象,然后我无法访问它们。 (我拿出了.display()函数调用来测试这个,并添加了一个简单的“创建对象”对象;将其添加到构造函数中以检查是否已创建了一些东西)。如何访问从文件输出创建的obect实例?

但是,试图访问个人对象给我错误:尝试访问对象成员函数时,“标识符”未定义。我可能正在做一些完全错误的事情,我希望推动正确的方向,我试图改变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; 

}; 

回答

0

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

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

另一个小问题是,您正在循环范围内重用变量名line(您之前声明为std :: string)。这可能有用,但是很混乱,应该避免。调用你的指针变量,如attItem

例如:

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

您的arent发送任何您收到的信息创建新的对象。添加一个构造函数与信息的字符串,然后初始化Attributes像这样:

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

另外,我建议不要让你的Attributes对象具有相同的名称保存数据的变量。即使它是无害的(我不确定它是什么),它只是不太干净。

+0

对不起,我应该可能进一步了解我的详细信息...我已经添加了该类的头文件,我只是试图测试是否可以创建更干净的代码通过使用数据文件创建对象,如果这是有道理的?那可能吗? – Iskardes

+0

你的意思是,在程序运行之前创建对象? – taylorc93

+0

基本上......是的,我想! – Iskardes

0

C和C++不允许在运行时创建的变量的新名称。因此health.display();中的health不能来自读取文件。

你可以做的是收集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; 
    ... 
}