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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With