[英]C++/multiple files with vector of object pointers
通過看下面的代碼,這個問題的基本思想應該很有意義,但是我將盡力解釋。 基本上,我有兩個通過指針相互引用的類,然后這些類位於兩個單獨的頭文件中。 該程序僅在沒有將類型為b的指針的矢量添加到Ah的部分下才能運行
#include <iostream>
#include "A.h"
#include "B.h"
using namespace std;
class a;
class b;
int main()
{
a* oba = new a;
b* obb = new b;
oba->set(obb,9);
obb->set(oba,0);
cout<<oba->get()<<endl;
cout<<obb->get()<<endl;
delete obb;
delete oba;
return 0;
}
//This is the A.h, look for the comment in the code where the error occurred.
#ifndef _A
#define _A
#include "B.h"
#include <vector>
class b;
class a
{
private:
b* objb;
int data;
vector <b*> vecb;//this is not well liked by the compiler???
public:
void set(b* temp, int value);
int get();
};
void a::set(b* temp, int value)
{
objb = temp;
data = value;
}
int a::get()
{
return data;
}
#endif
#ifndef _B
#define _B
#include "A.h"
class a;
class b
{
private:
a* obja;
int data;
public:
void set(a* temp, int value);
int get();
};
void b::set(a* temp, int value)
{
obja = temp;
data = value;
}
int b::get()
{
return data;
}
#endif
您不應該在Bh
#include "Ah"
,反之亦然,否則您將得到循環依賴。
請嘗試以下操作:
(啊)
class B; // forward declaration
class A
{
B* pb;
...
}
(A.cpp)
#include "A.h"
#include "B.h"
...
(Bh)
class A; // forward declaration
class B
{
A* pa;
...
}
(B.cpp)
#include "A.h"
#include "B.h"
...
HTH。
使用std名稱空間限定vector。
class a
{
...
std::vector<b*> vecb;
};
我添加了std::vector <b*> vecb;
到最初發布的代碼,並且編譯良好。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.