Declaring class objects in a header file

前端 未结 3 1848
渐次进展
渐次进展 2021-01-12 05:11

Greetings everyone.

I seem to be snagging on a fundimental but I cant find the solution anywhere. Anywho, will go ahead and explain.

I have a program consist

相关标签:
3条回答
  • 2021-01-12 05:42

    Declare Obj1 and Obj2 in your .cpp instead of at .h

    add.h

    class SA {
     ...
    public
        int x;
    };
    

    main.cpp

    #include "additional.h" 
    
    SA Obj1, Obj2;
    
    int main() {
    
     Obj1.x = 5;
    
     ...
    }
    

    If you want to declare Obj1 and Obj2 in your .h file, add extern in the .h file like so:

    extern SA Obj1, Obj2;
    

    but you should declare the objects in a .cpp file in your project:

    main.cpp

    SA Obj1, Obj2;
    

    The reason for this is that everytime you include the .h file, you are declaring Obj1 and Obj2. So if you include the .h file two times, you will create two instance of Obj1 and Obj2. By adding the keyword extern, you are telling the compiler that you have already decalred the two variables somewhere in your project (preferably, in a .cpp file).

    0 讨论(0)
  • 2021-01-12 05:47

    You can also have the following line of code in your header file:

    static SA Obj1, Obj2;
    

    This will create only 1 instance of each object at run time and prevent redefinitions. However, keep in mind that all files that include the .h file will be using the same instance of those two objects so you will need to be careful when you are accessing them.

    0 讨论(0)
  • 2021-01-12 05:52

    Use extern keyword. Declare these public objects as extern in header, then define instances in one of the cpps.

    Like this:

    extern SA Obj1; // in header
    
    SA Obj1;// in any one (no more than one) cpp
    
    0 讨论(0)
提交回复
热议问题