Error: has an initializer, but an incomplete type

I have a problem: it has an initializer, but an incomplete type when using struct:

in the hpp file:

class A { private: struct videoDT; }; 

in cpp file:

 struct A::videoDT { videoDT(int b) : a(b){} int a; }; void test() { struct videoDT test(1); } 

Then I have a problem:

Error: has an initializer, but an incomplete type

Thanks in advance

+6
c ++
source share
3 answers

I think the problem is that test() does not have access to A private types.

This compiles for me:

 class A { private: friend void test(); struct videoDT; }; struct A::videoDT { videoDT(int b) : a(b){} int a; }; void test() { A::videoDT test(1); } 
+5
source share

In your test function, you declare a local struct videoDT type, but you never define it. Not surprisingly, the compiler complains about initializing an object of an incomplete type. The end of the story.

How did you expect this to work? If you want your declaration to use the A::videoDT , then you should have used a qualified name for the type - A::videoDT - since that type was called. However, the code will not compile in any case, since A::videoDT is closed in A , and test does not have access to it.

In other words, it’s hard to understand what you were trying to do. Provide some clarification or code that makes more sense.

+3
source share

When the compiler processes the .hpp file, it needs to determine the size of the memory and the layout of class A. For this reason, it needs to know the memory layout of struct videoDT.

A compiler error complaining that it does not know what struct videoDT is because you define it in a .cpp file.

To resolve this error, you need to define a struct in the .hpp file that will be included before your original .hpp. Alternatively, you can use the pimpl idiom and change class A to:

 class A { private: struct videoDT* pVideoDT; } 

If you do this, you will no longer need to define the structure in the header file just to compile class A. However, the pimpl idiom is an advanced technique, and I suggest reading it before deciding to use it.

0
source share

All Articles