简体   繁体   中英

Forward Declaration of class in C++, incomplete type

I have an issue with Forward Declaration in C++ using clang compiler. Here is my code. It points data in CReference member as incomplete type. Please Help

class Internal;

class CReference {
private:
    Internal data;
public:

    CReference () {}    
    ~CReference (){}
};

class Internal {
public:
    Internal () {}
    ~Internal () {}
};

Forward declarations are useful when the compiler does not need the complete definition of the type. In other words, if you change your Internal data; to Internal* data or Internal& data , it will work.

Using Internal data; , the compiler needs to know the whole definition of Internal , to be able to create the structure of CReference class.

前向声明仅允许您使用指针和对它的引用,直到完全声明可用

To use a type as a member of a class the compiler has to know how big it is, so that the size of the class can be correctly calculated. A forward declaration doesn't provide that information (C++ won't look ahead and try to find it, especially since the body might be declared in another translation unit), so you can't use it as a by-value member.

You can use a pointer or a reference instead, because pointers and references are the same size no matter what type they refer to. Then the compiler only needs to know the size of that type once you start manipulating it, and so you can get away without the full declaration until then.

As mentioned above. Forward declaration has it's use to avoid header hell in header files when using only a plain pointer of a class in the header.

You usually want to keep includes in header files as few as possible. This can be achieved by forward declaring a class, but only if it is not a nested class and only if the pointer is used in header, as for this the pointer size is the required information, which is provided by the forward decl.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM