An in depth analysis of c and c++ static keywords
- 2020-06-07 05:00:52
- OfStack
static keyword
1, static member variable
static member variables do not open up memory space with object creation. That is, the static member variable is one regardless of which object it is viewed from.
2. static member method
Non-static member methods cannot be called from static member methods.
static member methods can be called from non-ES18en member methods.
Reason: There is no this pointer in non-ES22en member methods, so you cannot pass the this pointer when calling non-ES24en member methods inside. static member methods do not require the this pointer.
Important: Initialize the static member variable outside of the class.
#include <iostream>
using namespace std;
class Test{
friend void fun(const Test &t);
public:
Test(int d = 0) : data(d){
count++;
}
~Test(){
count--;
}
private:
int data;
static int count;
};
void fun(const Test &t){
cout << t.data << endl;
cout << Test::count << endl;
}
// Initialize the static Member variables
int Test::count = 0;
int main(){
//int Test::count = 0;// Compile, however, must be initialized outside static Member variables
//Test::count = 0;// Compile, however, must be initialized outside static Member variables
Test t(10);
fun(t);
Test t1(11);
fun(t1);
}
conclusion