c++ static关键字总结
1.类中的static关键字
#include <iostream>
using namespace std;
class Person
{
public:
static int person_num;
//Person() { person_num = 0; }
virtual void print() {};
};
int Person::person_num = 0;
class Man :public Person
{
public:
Man() { person_num++; }
void print()
{
cout<< person_num << endl;
}
};
class Woman :public Person
{
public:
Woman() { person_num++; }
void print()
{
cout << person_num<< endl;
}
};
int main()
{
Man* man1 = new Man();
Person *p1 = man1;
p1->print();
Woman* woman1 = new Woman();
p1 = woman1;
p1->print();
delete man1;
delete woman1;
system("pause");
}
这里Person类中的person_num static成员会被父类及子类实例所共用,有点类似原子操作。
2.函数中的static变量
void func()
{
static int num = 0;
num++;
cout << "func num:" << num << endl;
}
int main()
{
int num = 10;
func();
func();
cout << "main num:" << num << endl;
system("pause");
}
//func num:1
//func num:2
//main num:10
可以通过此例,体会下static变量的作用范围。