gpt4 book ai didi

C++/带有对象指针 vector 的多个文件

转载 作者:太空宇宙 更新时间:2023-11-04 14:25:15 25 4
gpt4 key购买 nike

这个问题的基本思想应该通过查看下面的代码来理解,但我会尝试解释。基本上我有两个类,它们通过指针相互引用,然后这些类位于两个单独的头文件中。该程序仅在没有将类型 b 指针的 vector 添加到 A.h 的部分时才有效。

#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

最佳答案

使用 std 命名空间限定 vector 。

class a
{
...
std::vector<b*> vecb;
};

关于C++/带有对象指针 vector 的多个文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4480199/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com