开发者

C++/multiple files with vector of object pointers

开发者 https://www.devze.com 2023-01-31 01:57 出处:网络
The basic idea of this problem should make sense by looking at the code below but I\'ll try to explain. Basically I have two classes which reference each other via pointers and then these classes are

The basic idea of this problem should make sense by looking at the code below but I'll try to explain. Basically I have two classes which reference each other via pointers and then these classes are in two separate header files. The program only works without the part where a vector of type b pointers is added into 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;  
开发者_StackOverflow
    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  


Qualify vector with std namespace.

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


You shouldn't #include "A.h" in your B.h, and vice versa, otherwise you get circular dependencies.

Try the following:

(A.h)

class B; // forward declaration
class A
{
    B* pb;
    ...
}

(A.cpp)

#include "A.h"
#include "B.h"
...

(B.h)

class A; // forward declaration
class B
{
    A* pa;
    ...
}

(B.cpp)

#include "A.h"
#include "B.h"
...

HTH.


I added std::vector <b*> vecb; to the code first posted and it compiled fine.

0

精彩评论

暂无评论...
验证码 换一张
取 消