Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

why can't use the 'link' as a name of class

Tags:

c++

class

As the title mentioned. The following code shows 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 is

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 this 'link test' statement, then everything is ok. Besides, if I replace 'link' with other name like 'Link', everything is ok too.

In Visual Studio or VC, the code is ok.... So it confused me very much.

like image 313
alfredtofu Avatar asked Mar 28 '13 08:03

alfredtofu


1 Answers

To summarize the comments: GCC includes a function named link. For C compatibility, C++ allows you to define a struct (or class) with the same name as a function, but you have to disambiguate them on use.

I.e. in this case, the fix is class link test;

The use of link inside the definition of class link is an exception, there it always refers to the class itself. This is necessary to be able to write the constructor, as you can't disambiguate the name there. There's no syntax which would allow it.

like image 187
MSalters Avatar answered Oct 14 '22 01:10

MSalters