C ++ - 2 classes 1 file

Suppose I want something like this in a single source file .cpp:

class A {
    public:
        void doSomething(B *b) {};
};

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

Is there a way to do this without breaking it into two separate files and not getting a compiler error (syntax error on doSomething(B *b))

+5
source share
8 answers

enter in the first line:

class B;
+22
source

If I remember well, you can “pre-declare” your class B.

class B; // predeclaration of class B

class A
{
   public:
      void doSomething(B* b);
}

class B
{
    public
      void doSomething(A* a) {}
}

public void A::doSomething(B* b) {}

Then your class “A” knows that class “B” will exist, although it is not yet defined.

The forward declaration is indeed the right term, as Evan Teran mentions in the comments.

+12
source

class B;
or
class A;

void doSomething(B *b)

B. , doSomething A

+4

. :

class B; // add this line before A declaration

class A {
    public:
        void doSomething(B *b) {};
};

class B {
    public:
        void doSomething(A *a) {};
};
+3

++ FAQ Lite . , , .

+3

,

class B;
class A {
  void Method( B* );
};
class B{
};

but you can only specify a pointer and reference variables for B. If you want more (for example, a method that separates the variable B *), you can provide only an declaration and define methods later in the same file - in the place where the declaration is already available classes.

+1
source

You need to forward ad B.

class B; 

class A
{
public:        
   void doSomething(B *b) {}
};

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

(And BTW, you don't need half-colons after the member function curly braces. :))

+1
source

Add another declaration B to A:

class B;

class A {
    public:
        void doSomething(B *b) {};
};

class B {
    public:
        void doSomething(A *a) {};
};
0
source

All Articles