Why can data be specified as a class type only if the class is defined? (from the book "C ++ primer")

The C ++ primer book has a section on class declarations and definitions. I do not understand everything in this sentence:

data members can only be specified as a class type if the class is defined.

I do not understand the logic of this proposal. How to specify a data member for a class type, what does this action mean?

+4
source share
3 answers

This means that declaring a class member of a non-static class as class type T Trequires complete .

( , T .)

.

class foo;    // forward declaration
class bar {
    foo f;    // error; foo is incomplete
};

,

class foo {}; // definition
class bar {
    foo f;    // fine; foo is complete
};
+8

, , :

 class A
 {
 public:
     A() {/* empty */}
 };

 class B
 {
 public:
     B() {/* empty */}

 private:
     A myClassMember;  // ok
 };

.... :

 class A;  // forward declaration only!

 class B
 {
 public:
     B() {/* empty */}

 private:
     A myClassMember;   // error, class A has only been declared, not defined!
 };
+3

, member , A , :

class A;

class B {
  A member;
};

, , , sizeof(A) .

, , , A :

class A {
  int value;
};

class B {
  A member;
};

, A ( ), member , :

class B {
  A* member;
};
+2

Source: https://habr.com/ru/post/1668897/


All Articles