C/C++ programming: incomplete types

definition

An incomplete type is a type that lacks enough information such as length to describe a complete object. In other words, if the compiler can calculate the size of a type at compile time, then it is a complete type, otherwise it is an incomplete type

In fact, we often use incomplete types in actual engineering design, but we don't know that there is such a concept. Forward declaration is a commonly used incomplete type:

class base;
struct test;

Base and test only give declarations, not definitions. Incomplete types must be supplemented in some way before they can be used for instantiation, otherwise they can only be used to define pointers or references, because at this time the pointer or reference itself is instantiated , not the base or test object.

An array of unknown length is also an incomplete type:

extern int a[];

Extern cannot be removed because the length of the array is unknown and cannot appear as a definition.

example

For example, the following forward declaration, when the compiler encounters it, it cannot determine how much space the student type occupies, so it is an incomplete type:

struct student *ps;

When the compiler encounters the definition of student, it becomes a complete type

struct student
{
    
    
    int num;
}    

How to determine if a type is a complete type (complete type)

As long as sizeof(T) can be calculated correctly for a type, this T is a complete type.

So to determine whether T is a complete type of template function can be written as follows:

other

Class forward declaration

  • The forward declaration of the class simply means to tell the current file that there is such a class. But the specific structure of this class, member functions, etc. are unknown. It can only be used to declare a reference or pointer to a class in the current file, and it cannot be instantiated. Because of this situation

reference

Guess you like

Origin blog.csdn.net/zhizhengguan/article/details/114948642