我创建了一个 A 类和一个 B 类,我试图在 A 中设置一个 B 类型的 vector ,在 B 中设置一个 A 类型的 vector :
A 类 header :
#ifndef A_H_
#define A_H_
#include "B.h"
#include <vector>
using namespace std;
class A {
public:
vector<B> bvector; // here is the error
A();
};
#endif /* A_H_ */
B 类 header :
#ifndef B_H_
#define B_H_
#include "A.h"
#include <vector>
using namespace std;
class B {
vector<A> aVector; //Here is the error
public:
B();
};
#endif /* B_H_ */
但是我得到以下错误:
"..\src/B.h:16:8: error: 'A' was not declared in this scope
..\src/B.h:16:9: error: template argument 1 is invalid
..\src/B.h:16:9: error: template argument 2 is invalid"
如果我删除 B 中的坏行,它会翻转到 A.h
。我做错了什么?
最佳答案
ive created a class A and a Class B, im trying to set a vector of type B in A, and a vector of type A in B
您正在创建一个 circular dependency在你的课之间。这通常是一件坏事,尤其是在 C++ 中。
为了编译 A,编译器需要知道 B 的定义(#include "B.h")。不幸的是,B header 包含对 A 类的引用(这里是循环引用)。 编译器无法处理这种情况,因为 A header 已包含在当前 TU 中(请参阅包含保护)。
尽管经常有循环引用是糟糕设计的征兆,但您最终可以使用前向声明来克服这个问题。 例如,您可以这样修改 B:
#ifndef B_H_
#define B_H_
#include <vector>
using namespace std;
class A; //forward declaration of class A
class B {
vector<A*> aVector; //note that you must only use pointer to A now
public:
B();
};
#endif /* B_H_ */
使用前向声明基本上告诉编译器类型 A 将在其他地方定义。编译器可以依赖这个事实,但它对 A 一无所知(特别是它忽略了 A 的大小及其方法)。 所以在 B 内部,如果你向前声明了 A,你只能使用指向 A 类的指针(指针总是有相同的大小)并且你不能从 B 内部调用 A 类的任何方法。
关于c++ - 在 B 类中使用 A 类类型的 vector ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13223430/