Declare an object even before that class is created

前端 未结 5 690
没有蜡笔的小新
没有蜡笔的小新 2021-02-04 14:03

Is there anyway to declare an object of a class before the class is created in C++? I ask because I am trying to use two classes, the first needs to have an instance of the sec

5条回答
  •  甜味超标
    2021-02-04 14:24

    You can't do something like this:

    class A {
        B b;
    };
    class B {
        A a;
    };
    

    The most obvious problem is the compiler doesn't know how to large it needs to make class A, because the size of B depends on the size of A!

    You can, however, do this:

    class B; // this is a "forward declaration"
    class A {
        B *b;
    };
    class B {
        A a;
    };
    

    Declaring class B as a forward declaration allows you to use pointers (and references) to that class without yet having the whole class definition.

提交回复
热议问题