Why are static member functions called only in the global scope if they have a return value?

I found something peculiar: static member functions of a class / structure cannot be called a global scope if they do not have a return value.

This program does not compile:

struct test
{
  static void dostuff()
  {
      std::cout << "dostuff was called." << std::endl;
  }
};

test::dostuff();

int main()
{  
   return 0;
}

Providing us with the following in GCC v4.8.3:

main.cpp:12:16: error: expected constructor, destructor, or type conversion before ';' token
test::dostuff();
               ^

However, adding the return value to dostuff()and assigning it to a global variable, the program compiles and works as intended:

struct test
{
  static int dostuff()
  {
      std::cout << "dostuff was called." << std::endl;
      return 0;
  }
};

int i = test::dostuff();

int main()
{
   return 0;
}

This gives the expected result:

dostuff was called.

Can someone explain to me why this is so, and if there is a workaround that is not related to creating global variables?

+4
source share
2 answers

, [basic.link]

( 2), . .

test::dostuff(); , ( , - ) , -, , ..). , int i = test::dostuff(); - : i int . . , , dostuff() , - , .

+4

++, . "" , main, .

, main, ( ) , i . " , ". - , : " ".

, main. , . , - . , main.

+2

All Articles