循环依赖......如何解决?

Nov*_*tor 1 c++ dependencies circular-dependency

我认为我有一个循环依赖问题,并且不知道如何解决它....尽可能短:我编写类似html解析器的东西.我有一个main.cpp文件和两个头文件Parser.h和Form.h. 这些头文件包含整个定义......(我懒得制作相应的.cpp文件......

Form.h看起来像这样:

//... 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
Run Code Online (Sandbox Code Playgroud)

和Parser.h看起来像这样:

// 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
Run Code Online (Sandbox Code Playgroud)

不知道它是否重要,但我正在使用MS Visual Studio Ultimate 2010进行构建,它会抛出'Parser':不是类或命名空间名称

如何解决这个问题呢?谢谢!

hat*_*ero 5

你可能想要做的是将方法声明保留在标题中

class Form {
public:
    void parse (stringstream& ss);
// ....
};
Run Code Online (Sandbox Code Playgroud)

并在源文件(即Form.cpp文件)中定义方法,如此

#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(); // >
}
Run Code Online (Sandbox Code Playgroud)

这应该解决你看到的循环依赖问题......