What gives such a design?
extern class Class obj {}; What gives such a design?
extern class Class obj {}; This is an erroneous record that the compiler should have warned you about. extern (in such a key) is applied only to variables and functions, and you have neither one nor the other. If we modify the example a little:
extern class Class { } instance; , it turns out that we declared an instance variable of type Class .
The code above is just an abbreviated form of such a record:
class Class { }; extern Class instance; Those. we defined a new class Class and declared an object of type Class named instance . Somewhere we have to define this object, otherwise when using it we will get an error at the layout stage.
Class in this entry? - ixSciTo the question why the word extern generally needed:
Suppose we have some global variable int var , this variable is one for the whole program (let's leave the question about the undesirability of global variables behind the scenes, the example is synthetic). A project consists of several .cpp files, each of which needs access to this variable. How to implement?
Option 1
// header.h void foo(); int var; // foo.cpp #include "header.h" int var = 42; void foo() { var = 42; } // main.cpp #include <iostream> #include "header.h" int main() { foo(); std::cout << var; } But no, when compiling we get this:
foo.cpp:4:5: error: redefinition of 'int var' int var; ^~~ In file included from foo.cpp:2:0: header.h:5:5: note: 'int var' previously declared here int var; ^~~ This is all because we need to declare a variable in the header file, and we define it.
In header.h next to the variable, we declared the function foo:
void foo(); In fact, we told the compiler - "This is what the foo function looks like, but its definition will be later (possibly in another file)." How to say the same about variables?
We need a tool for declaring variables.
That is the extern . Change one line in header.h :
// header.h void foo(); extern int var; And everything works:
$ g++ main.cpp foo.cpp $ a.exe 42 extern works with functions, in fact these two declarations are equivalent:
extern void foo(); // так обычно не пишут, но это верно void foo(); Starting with C ++ 11, there is another use case.
extern works only with functions and variables, but not with classes / structures, your construction does not make sense (and will not compile). If you need to declare a class, you need to write like this
class Foo; struct Bar; PS Another extern is used for a bunch of C ++ with C (and other languages), but that's another story ...
Source: https://ru.stackoverflow.com/questions/707854/
All Articles