我的搜索让我相信我遇到的问题被称为循环冗余。我不明白任何发布的解决方案。我是C++的(相当)新手,来自强大的Java背景。C++类相互依赖导致循环依赖性错误
基本上有两个类彼此依赖。 A类包含B类对象的向量,而B类包含需要A类对象作为输入的方法。
下面是重现问题的代码。
根据codelite g ++,错误在school.h中,并且“person没有在此范围内声明”。它还说“模板参数1无效”和“模板参数编号2无效”。然后是其他几个关于所有被调用的向量函数的非类型“int”。
的main.cpp
#include <iostream>
#include <string>
#include "person.h"
#include "school.h"
int main() {
person p;
school s;
std::cout << p.name << std::endl;
s.personVect.push_back(p);
std::cout << s.personVect.size() << std::endl;
std::cout << s.personVect.at(0).name << std::endl;
p.test();
return 0;
}
school.h
#ifndef SCHOOL_H
#define SCHOOL_H
#include <vector>
#include "person.h"
class school
{
public:
school();
~school();
std::vector<person> personVect;
};
#endif // SCHOOL_H
school.cpp
#include "school.h"
school::school(){}
school::~school(){}
person.h
#ifndef PERSON_H
#define PERSON_H
#include <string>
#include <vector>
#include "school.h"
class person {
public:
std::string name;
std::string phone;
school doSomethingWithSchool();
void test();
person();
~person();
};
#endif // PERSON_H
person.cpp
#include "person.h"
#include <iostream>
using namespace std;
person::person()
{
name = "marcus";
phone = "0400000000";
}
person::~person()
{
}
void person::test() {
cout << this->name;
}
school person::doSomethingWithSchool() {
school s;
}
你忘了问一个问题。是“如果我需要这种功能,我该怎么办?”? – Vesper 2013-03-28 06:16:20