Why can't a nested class have a member that is a type of an incoming class?

One of the methods of the class Cmust return struct, containing a pair of integers and a new instance C. This may seem uncomfortable, but given the overall design, it makes a lot of sense (think of a class Waveformthat returns a range of itself as a copy indicating where the range starts and ends).

The problem is that this does not seem to be resolved. I can redesign my class to get around this problem, but can you explain to me why , from the point of view of the compiler, it is impossible to do

struct S {
    struct S2 {
        S s;
    };
};

as Sis an incomplete type (this is a compiler error), and instead it is completely normal

struct C {
    struct C1 {
        C makeC() { return C(); }
    };
};

Where is the significant difference?

+4
5

, S::S2, S - , . .

:

struct S
{
    struct S2;   // declare only, don't define

    // ...
};

struct S::S2
{
    S s;         // now "S" is a complete type
};

, ++ . , :

struct X
{
    struct Y { X a; };

    int b[sizeof(Y)];      // "sizeof" requires a complete type
};
+5

, ( ). , . , .

, . :

struct S {
    struct S2;
};

struct S::S2 {
    S s;
};

S , .

- , , . - . .

+2

, , :

struct S {
    struct S2 {
        S s;
    };
    S2 s2;
};

S S2 . , , .

, , , . S2 S, . S& , S. , . .

+1

.

S* s;, .

0

, , .

, S S , S.

, C , .

struct C {
    struct C1 {
        C makeC();
    };
};

inline C C::C1::makeC() {
    return C();
}

This means that the compiler automatically “defers” the body of the function. For the declare function, the compiler needs to know only that it Cis a type, but it works if it Cis incomplete, namely to this point. When the definition command is compiled, the type is Cnow complete.

0
source

All Articles