简体   繁体   中英

In c++ how can I make class to recognize structures without including the header?

Hello I have class AA.h and inside I have defined structure:

#include "BB.h"

Struct  foo{

};

Class AA 
{
…
void funa()
{
    BB bb;
    foo f;
    bb.func(f);
}
….
};

My question is do I have to include the AA.h also in the BB.h file so it will recognize the foo struct or there is something else I can do ?

Seems simplest is to create a header for your struct then include it in both your AA and BB.

#ifndef __FOO__H__
#define __FOO__H__
struct foo {

};
#endif

I guess you want to use foo in BB.h . But you can not include AA.h in BB.h as it will introduce a cyclic dependency and the compilation will fail. The simplest way to solve this is to provide the implementation of A::funa in a separate source file (normally with .cpp extension). You just need to declare funa(); in the header file without any implementation. If you do this, then there is no need to include BB.h in AA.h (You need to include BB.h in AA.cpp ) thus avoiding the cyclic dependency.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM