我有两个互相引用的类。类B有一个指向A对象的指针列表,每个A对象都需要一个指向创建它的B对象的指针。为什么在单个文件中写入时会编译,而在拆分为多个文件时却不能编译?
namespace.h
#ifndef NAMESPACES_H
#define NAMESPACES_H
#include "A.h"
#include "B.h"
#include "C.h"
namespace NAMESPACE
{
class A;
class B;
class C;
}
#endif
A.h
#ifndef A_H
#define A_H
#include "namespaces.h"
#include <iostream>
namespace NAMESPACE{
class A
{
private:
int x;
B* ptrB;
public:
void print();
A(int g_x, B* g_ptrB);
};
}
#endif
A.cpp
#include "A.h"
namespace NAMESPACE{
A::print()
{
std::cout<<"I am class A, my x = "<<x<<std::endl;
}
A::A(int g_x, B* g_ptrB)
{
x = g_x;
ptrB = g_ptrB;
}
}
B.h
#ifndef B_H
#define B_H
#include "namespaces.h"
#include <vector>
#include <iostream>
namespace NAMESPACE{
class B
{
private:
std::vector<A*> vA;
public:
B(int g_x);
void print();
};
}
#endif
B.cpp
#include "B.h"
namespace NAMESPACE{
B::B(int g_x)
{
vA.push_back(new A(g_x, this));
}
void B::print()
{
std::cout<<"I am class B\n";
vA[0]->print();
}
}
main.cpp
#include <iostream>
#include "namespaces.h"
int main()
{
B *b = new B(3);
b->print();
return 0;
}
/ *相比之下,这个单个.cpp文件可以很好地编译* /
#include <iostream>
#include <vector>
class B;
class A
{
private:
int x;
B* ptrB;
public:
void print()
{
std::cout<<"I am class A, my x = "<<x<<std::endl;
}
A(int g_x, B* g_ptrB)
{
x = g_x;
ptrB = g_ptrB;
}
};
class B
{
private:
std::vector<A*> vA;
public:
B(int g_x)
{
vA.push_back(new A(g_x, this));
}
void print()
{
std::cout<<"I am class B\n";
vA[0]->print();
}
};
class C:public A
{
public:
C(int g_x, B* g_ptrB):A(g_x, g_ptrB){}
};
int main()
{
B *b = new B(3);
b->print();
return 0;
}
编译单独的文件时,出现很多错误,例如
In file included from namespaces.h:4:0,
from B.h:4,
from B.cpp:1:
A.h:11:2: error: ‘B’ does not name a type
B* ptrB;
^
A.h:14:13: error: ‘B’ has not been declared
A(int g_x, B* g_ptrB);
^
In file included from namespaces.h:6:0,
from B.h:4,
from B.cpp:1:
C.h:10:13: error: ‘B’ has not been declared
C(int g_x, B* g_ptrB):A(g_x, g_ptrB){}
但是当编译一个文件时,所有文件都运行顺利,我得到了
I am class B
I am class A, my x = 3
怎么来?