@class vs. #import

后端 未结 16 1088
渐次进展
渐次进展 2020-11-21 22:42

It is to my understanding that one should use a forward-class declaration in the event ClassA needs to include a ClassB header, and ClassB needs to include a ClassA header t

16条回答
  •  旧时难觅i
    2020-11-21 23:31

    Compiler will complain only if you are going to use that class in such a way that the compiler needs to know its implementation.

    Ex:

    1. This could be like if you are going to derive your class from it or
    2. If you are going to have an object of that class as a member variable (though rare).

    It will not complain if you are just going to use it as a pointer. Of course, you will have to #import it in the implementation file (if you are instantiating an object of that class) since it needs to know the class contents to instantiate an object.

    NOTE: #import is not same as #include. This means there is nothing called circular import. import is kind of a request for the compiler to look into a particular file for some information. If that information is already available, compiler ignores it.

    Just try this, import A.h in B.h and B.h in A.h. There will be no problems or complaints and it will work fine too.

    When to use @class

    You use @class only if you don't even want to import a header in your header. This could be a case where you don't even care to know what that class will be. Cases where you may not even have a header for that class yet.

    An example of this could be that you are writing two libraries. One class, lets call it A, exists in one library. This library includes a header from the second library. That header might have a pointer of A but again might not need to use it. If library 1 is not yet available, library B will not be blocked if you use @class. But if you are looking to import A.h, then library 2's progress is blocked.

提交回复
热议问题