Why can't I multi-declare a class

前端 未结 9 1280
我在风中等你
我在风中等你 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条回答
  •  梦毁少年i
    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.

提交回复
热议问题