C++ - 2 classes 1 file

后端 未结 8 2018
南旧
南旧 2021-01-19 03:11

Suppose I want something of this sort, in one .cpp source file:

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

class B {
    publi         


        
相关标签:
8条回答
  • 2021-01-19 03:18

    You need to forward declare B.

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

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

    0 讨论(0)
  • 2021-01-19 03:21

    You can try a forward declaration like

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

    but you will only be able to declare pointer and reference variables for B then. If you want more (like a method that dereferences B* variable) you can provide a declaration only and define methods later in the same file - at the point where both classes declaration is already available.

    0 讨论(0)
  • 2021-01-19 03:23

    put at the first line:

    class B;
    
    0 讨论(0)
  • 2021-01-19 03:26

    The C++ FAQ Lite answers this question and others. I'd seriously considering reading that thing end to end, or getting the book and doing the same.

    0 讨论(0)
  • 2021-01-19 03:34

    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 a class 'B' will exists, although it hasn't been really defined yet.

    Forward declaration is indeed the correct term, as mentionned by Evan Teran in the comments.

    0 讨论(0)
  • 2021-01-19 03:38

    Yes. You need a forward declaration:

    class B; // add this line before A's declaration
    
    class A {
        public:
            void doSomething(B *b) {};
    };
    
    class B {
        public:
            void doSomething(A *a) {};
    };
    
    0 讨论(0)
提交回复
热议问题