开发者

C++ method declaration, class definition problem

开发者 https://www.devze.com 2023-02-02 00:52 出处:网络
I have 2 classes: A and B. Some methods of class A need to use class B and the opposite(class B has methods that need to use class A).

I have 2 classes: A and B. Some methods of class A need to use class B and the opposite(class B has methods that need to use class A).

So I have:

class A;

class B {

   method1(A a) {
   }

}

class A {

   method1(B b) {
   }

   void foo() {
   }
}

and everything works fine.

But when I try to call foo() of class A from B::method1 like this:

class B {

   method1(A a) {
      a.foo();
   }

}

I get as result compile errors of forward declaration and use of incomplete type. But why is this happening? (I hav开发者_开发问答e declared class A before using it?)


The compiler hasn't seen the definition of A at the point where you call A::foo(). You can't call a method for an incomplete type - i.e. a type for which the compiler doesn't yet know the definition of. You need to define the calling method after the compiler can see the definition of class A.

class A;

class B 
{
    public:
   void method1(A a);
};

class A 
{
    public:
   void method1(B b) { }

   void foo() { }
};

void B::method1(A a)
{
    a.foo();
}

In practice, you may want to place the definition for B::method1() in a separate cpp file, which has an #include for the header file containing class A.


C++ INCLUDE Rule : Use forward declaration when possible.

  • B only uses references or pointers to A. Use forward declaration then : you don't need to include . This will in turn speed a little bit the compilation.

  • B derives from A or B explicitely (or implicitely) uses objects of class A. You then need to include

Source: http://www-subatech.in2p3.fr/~photons/subatech/soft/carnac/CPP-INC-1.shtml

For avoiding multiple inclusion of header files you should include a guard, to prevent the compiler from reading the definitions more that once:

#ifndef EMCQUEUE_HH
#define EMCQUEUE_HH
// rest of header file ...
// definition code here...
#endif

See Industrial Strength C++ Chapter Two: Organizing the code.

0

精彩评论

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

关注公众号