Why can't I use the โ€œlinkโ€ as the class name

As mentioned in the title. The following code shows the error:

#include <iostream> using namespace std; class link { public: link() { num=0; next=NULL; } int num; link* next; }; int main() { link test; return 0; } 

compile this code with

 g++ test.cpp -o test 

my g ++ versions

g ++ (Ubuntu / Linaro 4.6.3-1ubuntu5) 4.6.3

And the compiler shows the following error

 test.cpp: In function 'int main()': test.cpp:18:10: error: expected ';' before 'test' 

If I comment on this 'link test' statement, then everything will be fine. In addition, if I replace the โ€œlinkโ€ with another name, for example, โ€œLinkโ€, everything is fine too.

In Visual Studio or VC, the code is fine ... So that really confused me.

+6
source share
2 answers

To summarize the comments: GCC includes a function called link . For compatibility, C ++ allows you to define a structure (or class) with the same name as a function, but you must eliminate them when using.

those. in this case, the class link test; fix class link test;

Using link inside the class link definition is an exception; it always refers to the class itself. This is necessary in order to be able to write a constructor, since you cannot eliminate it there. There is no syntax to do this.

+1
source

There is an int link (const char * path1, const char * path2); function in unistd.h that seems to be included from iostream. In the past, Gcc had a problem with such a problem. (Note that 4.7.2 does not show this behavior.)

As noted by MSalters by adding

 class link test; 

should fix the problem.

0
source

All Articles