Why can't I multi-declare a class

前端 未结 9 1189
我在风中等你
我在风中等你 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:33

    The first (extern) makes a reference to an existing variable. So you are just indicating the variable twice.

    The class declaration gives meaning to a type (your class: A). You are trying to give two meanings to A. This is not of any use for you, and can only confuse, so the compiler protects you from it.

    Btw, if you put both classes in difference namespaces you can give them the same name.

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

    But in the first case ther is no contradiction.

    extern int i;
    extern double i;
    

    won't work either. So if you create class A to times it wouldn't be possible to decide who A is.

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

    I guess the real question is 'why would you want to?'. The situation sometimes arises when you include a header file multiple times in the same translation unit (.cpp file). If this is the case, you should look at using include guards to keep the compiler happy.

    Another reason that this might be causing problems for you is that you're using a 3rd-party library which defines classes whose names conflict with your own classes. In this case you should look at using namespaces to resolve the ambiguity.

    In both cases 'extern int i;' is referencing the same object (declared elsewhere) and so the multiple declarations are unambiguous. If you wrote:

    extern int i;
    extern float i;
    

    The compiler would complain about the ambiguity (because it wouldn't know which variable you intended to manipulate if you wrote 'i=0;'.

    Duplicate class declarations gives rise to the possibility that declarations are different; again, how would the compiler know which one to use when it encounters 'A foo;'? I guess the compiler could compare the class declarations and verify that they're infact identical, but this would be an awful lot of effort to go to when the alternative solutions (namespaces, include guards, renaming) are so much easier (and probably less confusing for whoever ends up reading the code).

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