Why can't I multi-declare a class

前端 未结 9 1190
我在风中等你
我在风中等你 2021-01-12 04:03

I can do this

extern int i;
extern int i;

But I can\'t do the same with a class

class A {
..
}
class A {
..
}
相关标签:
9条回答
  • 2021-01-12 04:23

    You can declare a class and an object multiple times, what you can't do is define it more than once.

    extern makes this a declaration and not a definition (because there is no initializer):

    extern int a;
    

    The body makes your class a definition and not just a declaration. You can define a class once.

    0 讨论(0)
  • 2021-01-12 04:24

    It has nothing to do with declarations vs definitions. The issue is types versus objects.

    extern int i;
    

    tells the program that at an object of type int exists, and its name is i. Because it is extern no storage is allocated for it here, but somewhere else, probably in another translation unit, it is defined and storage is allocated for it.

    class A {
    ..
    };
    

    defines a type named A. It doesn't allocate any objects or variables. It makes absolutely no difference at runtime, and no storage is allocated for it, because it is not an object. It simply introduces a new type to the compiler. From this point on, you are able to create objects of type A, and they will have storage allocated for them.

    0 讨论(0)
  • 2021-01-12 04:27

    The following are declarations:

    extern int i;
    class A;
    

    And the next two are definitions:

    int i;
    class A { ... };
    

    The rules are:

    • a definition is also a declaration.
    • you have to have 'seen' a declaration of an item before you can use it.
    • re-declaration is OK (must be identical).
    • re-definition is an error (the One Definition Rule).
    0 讨论(0)
  • 2021-01-12 04:29

    I gave it some thought. I realized class in not a data type, it is a enabler for defining a data type.

    So in

    extern int i;
    extern int i;
    

    int is a data type. So we are re-declaring a variable not a data type.

    But in

    class A {...};
    class A {...};
    

    A is a data type. And we are re-defining a data type, which is not allowed, of course.

    0 讨论(0)
  • 2021-01-12 04:31

    you can do

    class A;
    

    as often as you want and then in one file define it with

    class A { ... }
    

    Example for this:
    classB.h:

    class A;
    class B { A *a; }
    

    classA.h:

    class B;
    class A { B *b; }
    
    0 讨论(0)
  • 2021-01-12 04:33

    The closest equivalent to extern int i with a class is a forward declaration, which you can do as many times as you like:

    class A;
    
    class A;
    
    class A;
    
    class A{};
    

    When you define the actual class you are saying how much memory is required to construct an instance of it, as well as how that memory is laid out. That's not really the issue here, though.

    0 讨论(0)
提交回复
热议问题