问题
So i have a piece of code with a class like that:
#include<iostream>
#include<cstring>
class stu
{
static int proba;
public:
stu();
static int no(){
return proba;
}
};
int stu::proba=0;
stu::stu()
{
proba=proba+1;
}
int main()
{
std::cout<< stu::no << std::endl;
}
The output is 1.
It does so even if i change stu::no
so that it would be only {return 12;}
Why does it happen? How do I fix it??
回答1:
Change it to std::cout<< stu::no() << std::endl;
Without the ()
, I believe it's evaluating as a pointer, and not doing what you're expecting.
Edit: As pointed out by @Loomchild, using g++ -Wall
will provide further insight as to why it's always 1. The pointer to the static function is always evaluated as true
in this context, hence the value being printed.
回答2:
std::cout<< stu::no << std::endl;
prints the address of the function, you're not actually calling it.
std::cout<< stu::no() << std::endl;
calls the function and prints the return value.
In MSVS, this indeed produces a pointer value, with the overload operator << (void*)
.
回答3:
Use stu::no() instead of stu::no. Also, a minor thing really but if you put
using namespace std;
below the #includes you won't have to use std::
Just makes things a little more readable.
回答4:
stu::no
is a function that takes no arguments and returns int.
There is no operator<<
that takes functions with your particular signature, so the available overloads are considered. Long story short, the operator<<(ostream&, bool)
is the closest match, after function-to-pointer and pointer-to-bool conversions.
Since the function actually exists, its address is definitely non-zero, so the pointer to bool conversion always yields true
, which you see as 1
.
Make it std::cout<< std::boolalpha << stu::no << std::endl;
to see for yourself that it's really a boolean output.
Make it std::cout<< stu::no() << std::endl;
to print the result of the function call.
See How to print function pointers with cout? if you want to know what happened in more detail.
来源:https://stackoverflow.com/questions/13050673/c-static-method-output-using-cout-is-always-1