cyclic dependency … how to solve?

帅比萌擦擦* 提交于 2019-12-11 06:46:43

问题


I think I have a cyclic dependency issue and have no idea how to solve it.... To be as short as possible: I am coding something like a html parser. I have a main.cpp file and two header files Parser.h and Form.h. These header files hold the whole definitions... (I'm too lazy to make the corresponding .cpp files...

Form.h looks like this:

//... standard includes like iostream....

#ifndef Form_h_included
#define Form_h_included

#include "Parser.h"
class Form {
public:
    void parse (stringstream& ss) {

        // FIXME: the following like throws compilation error: 'Parser' : is not a class or namespace name
        properties = Parser::parseTagAttributes(ss);

        string tag = Parser::getNextTag(ss);
        while (tag != "/form") {
            continue;
        }
        ss.ignore(); // >
    }
// ....
};
#endif

and Parser.h looks like this:

// STL includes
#ifndef Parser_h_included
#define Parser_h_included

#include "Form.h"

using namespace std;

class Parser {
public:
    void setHTML(string html) {
         ss << html;
    }
    vector<Form> parse() {
        vector<Form> forms;

        string tag = Parser::getNextTag(this->ss);
        while(tag != "") {
            while (tag != "form") {
                tag = Parser::getNextTag(this->ss);
            }
            Form f(this->ss);
            forms.push_back(f);
        }
    }
// ...
};
#endif

Don't know if it is important, but I'm doing the build in MS Visual Studio Ultimate 2010 and it throws me 'Parser' : is not a class or namespace name

How to solve this problem? Thank you!


回答1:


What you probably want to do here is leave the method declaration in the header like so

class Form {
public:
    void parse (stringstream& ss);
// ....
};

And define the method in a source file (i.e. a Form.cpp file) like so

#include "Form.h"
#include "Parser.h"

void parse (stringstream& ss) {

    properties = Parser::parseTagAttributes(ss);

    string tag = Parser::getNextTag(ss);
    while (tag != "/form") {
        continue;
    }
    ss.ignore(); // >
}

That should resolve the cyclic dependency issue you're seeing...




回答2:


  1. Stop defining your member functions lexically inline in headers. Define them in source files.
  2. Now you can take advantage of forward declarations when you need them (you don't here).


来源:https://stackoverflow.com/questions/9435666/cyclic-dependency-how-to-solve

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!