Вопрос

I want to implement association I C++, but I am getting several errors and I am unable to solve them.

Class A{

public: //methods
private:
B * b_obj;

};

Class B{
public: //methods
private:
A * a_obj;
}

Both these classes are in separate files. i.e. A.h, A.cpp, B.h and B.cpp. VS2012 is giving errors Error C2061: syntax error near A

Это было полезно?

Решение 2

This particular cross-reference situation can be handled in multiple ways.

Assuming that you can't just let A.h include B.h and B.h include A.h because, when including headers at most once, one will be included always before the other, the simplest solution is just to use forward references:

A.h

class B;

class A {
  B* bObj;
}

A.cpp

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

...

B.h

class A;

class B {
 A* aObjM;
}

B.cpp

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

...

This simple solution doesn't allow you to use A specifications in B.h (eg calling a method) and vice-versa, nor it allows you to store concrete instances (A vs A*) in the B class but it doesn't sound like your case.

Другие советы

You'll need to forward-declare the classes:

A.h:

class B;

class A {
    public:
        // methods
    private:
        B* b_obj;
};

B.h

class A;

class B {
    public: 
        // methods
    private:
        A* a_obj;
};

What are the include statements you have for each file? From what you have here it looks like forward declaration is going to work for you.

// A.h
#includes without B.h

class B;

class A {
    public:
         // whatever

    private:
        B * b_obj;
};

// B.h
#includes without A.h

class A;

class B {
    public:
         // whatever

    private:
        A *a_obj;
};
Лицензировано под: CC-BY-SA с атрибуция
Не связан с StackOverflow
scroll top