项目由于指针卡住 [英] Project stuck due to pointers

查看:54
本文介绍了项目由于指针卡住的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

大家好,
希望你们都会成为f9.好吧,我是这个社区的新人,正在从事一个项目.我卡住了,没有找到解决方案.请帮我.我正在一个XML项目上,我必须从xml读取数据,然后必须生成一个代码(javascript),最后在HTML中使用此代码.我正在发布我的代码.(解析xml.h和解析xml.cpp ).

Hi Guys,
Hope u all will be f9. Well i m a new in this community and working on a project. I stucked and didn''t find the solution. Kindly help me out. I am working on an XML project i have to read the data from xml and then have to generate a code(javascript) and at last use this code in HTML.I am posting my code.(parse xml.h and parse xml.cpp).

parse xml.h
    #pragma once
    #include <vector>
    #include <iostream>
    #include <string>
    #include <map>
    #include <fstream>
    using namespace std;
    
    namespace prog {
    
    	class MainNode
    	{
    	public: 
    		vector<Mainnode*> *elements;
    		MainNode () { elements = NULL;}
    		virtual void writeCode(fstream &outfile) = 0; 
    		
    	};
    	   class ScxmlElement : public MainNode 
    	   {
    	   public:
    		  string version, initialstate, name;
    		  ScxmlElement () { elements = new vector<Mainnode*> ();}
    		  void writeCode(fstream &outfile){
          outfile<<"var JS"<<" "<<"= new Statechart"<<" "<<"("<<initialstate<<")"<<endl;
    			  
    			 </*for (auto it = elements->begin(); it != elements->end(); ++it) {
    				  (*it)->writeCode(outfile);
                delete *it;
        }*/ //i tried to use this but got error (debug assertion fail) and then left it>
    	for (long index=0;index<(long)elements->size();++index){
    		 outfile<<"index at element: "<<(*elements).at(index)<<endl;
    				  MainNode *node = elements->at(index);
    				  outfile<<node<<endl;
    				 node->writeCode(outfile);//i think this call has problem
    				 }
    		  }
    	    };
    		class ScxmlDatamodel : public MainNode
    		{
    		public: 
    			
    			map<string,string> data;
    			void writeCode(fstream &outfile){
    	for(map<string,string>::const_iterator it= data.begin();it!=data.end();++it)
    	 outfile<<"var"<<" "<<(*it).first<<" = "<<(*it).second<<endl;
    			}
    		};
    		class ScxmlState : public MainNode
    		{
    		public:
    			string id, module;
    			ScxmlState () { elements = new vector<Mainnode*> ();}
    			void writeCode(fstream &outfile){
    	outfile<<"\nvar"<<" "<<id<<"State = new State ("<<"\""<<id<<"\""<<")"<<endl;
    			
    	for (long index=0;index<(long)elements->size();++index){
    				  MainNode *node = elements->at(index);
    				  node->writeCode(outfile);
    				}
    				outfile<<"JS"<<".states[\""<<id<<"\"] = "<<id<<"State"<<endl;
    			}
    
    		};
    		class ScxmlTransition : public MainNode
    		{
    		public: 
    			string eventname, target;
    			string cond;
    			MainNode *parent;
    			void writeCode(fstream &outfile){
     outfile<<dynamic_cast<scxmlstate*>(parent)->id<<"State.handler[\""<<eventname<<"\"] = function (event) {";
    				if(!cond.empty())
    	outfile<<"\nif("<<cond<<") return \""<<target<<"\"\nelse return null\n}";
    				else if(!target.empty())
        		outfile<<"\nreturn \""<<target<<"\" }"<<endl;
    				else outfile<<"\nreturn null }"<<endl;
    			}
    		};
    }
    class Generator {
    public:
    	string path;
    	Generator (string filepath) { path=filepath; }
    	void write(prog::ScxmlElement module){
    		fstream file(path+"tictac_gen.js", ios::out | ios::app);
    		file<<"\ndocument.write('<script language=\"javascript\" type=\"text/javascript\"src=\"statemachine.js\"></script>')"<<endl;
    		module.writeCode(file);
    		file.close();
    	}
    };



我在解析后得到变量值.我在上面的代码中想要在向量元素"中存储来自xml和虚拟函数的内容,当从向量中检测到节点类型的值(将在相应类中检测到虚函数)时(应在相应的类中)但它没有发生. VS刚刚卡住,并转到调试器"pugixml parser.exe中0x7c919af2的未处理异常:0xC0000005:访问冲突写入位置0xdddddded.".经过很多努力后,我无法找到错误.如果有人指出我的错误,我将非常感谢您.其余代码如下.



I am getting the variable values after parsing. What i want in above code that in vector ''elements'' will be stored from xml and in the virtual functions when values, of node type from vector, will be detected the virtual function (in respective class) w.r.t that node should be called but its not happening. VS just stucked and go to debugger "Unhandled exception at 0x7c919af2 in pugixml parser.exe: 0xC0000005: Access violation writing location 0xdddddded.". After struggling a lot i m unable to find the error. If anyone will point out my error i will be very thank full you. The remaining code is as follows.

//parse xml.cpp
#include "parse xml.h"
#include "pugixml.hpp"
#include <cstdio>
using namespace pugi;
using namespace std;

class ScxmlParser
        {
        protected:
        xml_document doc;
        public:
            ScxmlParser () {}
            prog::ScxmlElement parse();
        };

        prog::ScxmlElement ScxmlParser::parse ()
           {
               xml_parse_result result = doc.load_file("C:\FILE.xml");
               xml_node xMainNode = doc.child("scxml");
               prog::ScxmlElement module;
               module.version=xMainNode.attribute("version").value();
               if(module.version.empty())
                throw string("Attribute version missing");
                           module.initialstate=xMainNode.attribute("initialstate").value() ;
               if(module.initialstate.empty())
                throw string("Attribute initialstate missing");

               module.name=xMainNode.attribute("datamodel").value();
               if(module.name.empty())
                throw string("Attribute datamodel missing");


         prog::ScxmlDatamodel datamodel;
         string id =xMainNode.child("datamodel").child("data").attribute("id").value();
         string expr=xMainNode.child("datamodel").child("data").attribute("expr").value();
          if(id.empty() || expr.empty())
           throw string ("Specified nodes or Attributes are missing");
         else datamodel.data.insert(make_pair(id,expr));
         module.elements->push_back(&datamodel);

         for(map<string,string>::const_iterator it=datamodel.data.begin();it!=datamodel.data.end();++it)


         xml_node states=xMainNode.child("state");
         prog::ScxmlState state;
         for(xml_node states=xMainNode.child("state");states;states=states.next_sibling("state")){
             state.id=states.attribute("id").value();
             if(state.id.empty())
                  throw string ("Attribute state id missing");
                  state.module=module.name;
                  module.elements->push_back(&state);


                 prog::ScxmlTransition transition;
                for(xml_node transitions=states.child("transition");transitions;transitions=transitions.next_sibling("transition")){
                       transition.eventname=transitions.attribute("event").value();
                       if(transition.eventname.empty())
                         throw string ("Attribute transition event missing");
                       string condition=transitions.attribute("cond").value();
                     if(!condition.empty()){
                          transition.cond=condition;
                          }
                      transition.target=transitions.attribute("target").value();
                      transition.parent=&state;
                      state.elements->push_back(&transition);


                  }
            }
        return module;
        }

void main(){
    ScxmlParser p;
    string getpath;
    prog::ScxmlElement e;
    cout<< "Enter file path"<<endl;
    cin >> getpath;

    try{ e=p.parse();} catch (string s) { cout << s << endl; }
    Generator gen(getpath);

    gen.write(e);
    getchar();

}



为了更好和快速地理解文本,我认为问题出在粗体字.请帮我.谢谢



For better and quick understanding text has been bold, where i think the problem lies. Kindly help me out. Thanks

推荐答案

您不会因为指针"而失败,但是由于混乱,您几乎分散了到处.

在您的代码中,各个类的作用尚不清楚.尚不清楚将派生用于运行时专业化还是扩展.

You''re not failing "because of pointers", but because of the confusion you have dispersed almost everywhere.

In you code the role of the various classes is not clear. As it is not clear if derivation is used for runtime-specialization or extension.

class MainNode
{
public:
    vector<mainnode*> *elements;
    MainNode () { elements = NULL;}
    virtual void writeCode(fstream &outfile) = 0;

};


向量中使用mainnode到底是什么?为什么通过指针实例化矢量?

你写


What the hell is mainnode used in vector? Why is the vector instantiated through a pointer?

You write

elements->at(index)


还要写


But also write

(*node).writeCode(outfile)


(为什么不是node->writecode(outfile)?请保持一致!)


(why not node->writecode(outfile)? Try to be consistent!)

You do

dynamic_cast<scxmlstate*>(parent)->id


但是,如果您使用dynamic_cast,则意味着您要检查节点的运行时类型是否为s sxcmlstate(这到底是什么?我看到的是ScxmlState,而不是scxmlstate).但是动态类型转换可能无法为NULL,但是您直接进行寻址id而不进行任何检查(但是,如果使用dynamic_cast检查类型,则具有ID的目的是什么?)

我的印象是,您正在自下而上地编写代码,推送语句,并尝试让所有内容自动进入其位置.

我建议您不要继续这样做(您迟早会陷入混乱,即使它可能会起作用,您也永远不会知道为什么会起作用,而且在它将停止工作的那一天,您将不知道该怎么做开始.

因此,请丢掉这些混乱的东西,从铅笔和纸开始,尝试弄清楚我们的类的作用,它们之间的相互关系,这些关系应如何在聚合机制中转换(嵌入一个有效变量,动态指向的指针).您必须销毁的已分配对象,指向其他人拥有的对象的指针……),然后开始编写类,成员以及适当的构造函数和析构函数(使用分配了分配对象的理智策略,如果对象是适当的所有权)已定义).

然后编写一个测试程序,检查所有关系是否正常工作,并且什么都没有忘记.

之后,开始对输入和输出函数进行编码,以根据适当的输入创建数据结构并写入适当的输出.


But if you dynamic_cast it means you want to check if the runtime type of a node is ans sxcmlstate (What the hell is it? I see a ScxmlState, but not a scxmlstate). But dynamic cast may fail to NULL, but you directly address id without any check (but if you use dynamic_cast to check the type, what is the purpose to have an id ??)

The impression I have is that you are coding bottom-up, pushing statements around and attempting to let everything go at its place automatically.

I suggest you not to continue that way (you will sooner or later with a big mess that even if it may work, you''ll never know WHY it works, and the day it will stop working you will have no clue about where to start for.

So throw away this mess, and start with pencil and paper, and try to fiugure out what the role of our classes is, how they relates to each other, how those relations should translated in aggregation mechanisms (embedding of a valie, pointer to dynamically allocated object you have to destroy, pointer to something owned by somebody else ...), then start writing classes, members, and proper constructor and destructors (with the sane policy that what is allocated is also deallocated, and a proper ownership if object is defined).

Then write a test program that checks that all the relations properly works and nothing had been forgot.

After that start coding input and output functions that creates the data structure based on proper input and write proper output.


我只是略过了您的帖子,实在太多了文字,但这里有几件事引起了我的注意:

1.除了虚拟成员函数外,不要在抽象基类中定义公共成员.构造函数和成员变量应始终受保护或私有.

2.养成为定义的每个类声明默认构造函数的习惯,并在该构造函数中初始化该类的每个成员变量.您是为MainNode这样做的,但其他人没有.

3.假定每个指针都可以为0,并在取消引用之前对其进行检查

4.为什么ScxmlElement在命名空间prog中而不在其他Scxml*类中?

5.您将地址存储到局部变量,而不是创建类的新实例.这是一个示例,但我至少看到了一个:
I''ve only skimmed over your posting, there''s just too much text, but here''s a few things that caught my attention:

1. Don''t define public members in an abstract base class except for virtual member functions. Constructors and member variables should always be protected or private.

2. Make a habit to declare a default constructor for each class you define, and in that constructor initialize every single member variable of that class. You did that for MainNode, but not the others.

3. Assume that every pointer may be 0, and check it before dereferencing

4. Why is ScxmlElement in namespace prog, but not the other Scxml* classes?

5. You''re storing addresses to local variables instead of creating new instances of your classes. Here is one example, but I''ve seen at least one more:
prog::ScxmlElement ScxmlParser::parse ()
{
//...
    prog::ScxmlTransition transition;
//...
    state.elements->push_back(&transition);
//...


非常感谢很多" Stefan_Lang" .主要问题是编名称空间".我正在做什么,用"new"实例化了几次类,但是每次我忘记添加"prog ::".在您回复后,我意识到我只有一个名称空间.再次感谢您,不便之处,敬请谅解.
Thanks very much "Stefan_Lang". Main problem was "prog namespace". what i was doing i use to instantiate the classes several time with "new" but every time i forgot to add "prog::". After your reply i realized that i have one namespace. Thanks again and also sorry for any inconvenience.


这篇关于项目由于指针卡住的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆