I just noticed that we can access c++ static member function by member-selection operator (. or –>)
for example:
class StaticTest
{
private:
int y;
static int x;
public:
StaticTest():y(100){
}
static int count()
{
return x;
}
int GetY(){return y;}
void SetY(){
y = this->count(); //#1 accessing with -> operator
}
};
Here are how to use
StaticTest test;
printf_s("%d\n", StaticTest::count()); //#2
printf_s("%d\n", test.GetY());
printf_s("%d\n", test.count()); //#3 accessing with . operator
test.SetY();
- what is the use case of #1 and #3?
- what is the difference between #2 and #3?
Another style of #1 for accessing static member function in member function is
void SetY(){
y = count(); //however, I regard it as
} // StaticTest::count()
But now it looks more like this->count(). Is there any difference of two style calling?
Thanks
Have a look at this question.
According to the standard (C++03, 9.4 static members):
So, when you already have an object and you’re calling a static method on it, then there is no difference to using the class member access syntax.
If you however need to create the object first (be it by instantiating the object directly before, or by calling some function), then this creation process will of course take up a little extra time and memory. The this-Pointer, however, is never passed in to a static function, the call itself is always the same, no matter how it was written.