关于没有类的c语言的static的作用:https://blog.csdn.net/sinat_27382047/article/details/71698157
静态成员变量:
——全类各个实例化对象所共有的。
静态数据成员初始化与一般数据成员初始化不同。静态数据成员初始化的格式为:
<数据类型><类名>::<静态数据成员名>=<值>
int Student::number=21;
这里还涉及变量生存期的问题,(对静态局部变量在编译时赋初值的,即只赋值一次,在程序运行时它已有初值。以后每次调用函数时不再重新赋初值而是只保留上次函数调用结束时的值。)详见我的:https://blog.csdn.net/sinat_27382047/article/details/71798956
静态成员函数:
——静态成员函数只能使用静态成员变量、局部变量,而不能使用普通成员变量。
<类名>::<静态成员函数名>(<参数表>)
Student::getDegree();
坑!:
static成员"Cannot declare member function …to have static linkage"错误
声明时需要注意【静态变量需要定义】:https://blog.csdn.net/zhangxiao93/article/details/51344195
(提一嘴,vs的错误动态提示真好用,直接就标出问题了。用gcc的我啊……)
test.h
#pragma once
class test
{
public:
static int state;//静态变量
test() {}
~test() {}
void func1();
static void func2();//静态函数
private:
};
test.cpp
#include <iostream>
#include "test.h"
using namespace std;
int test::state=0;//!静态变量需要定义,否则.h里的static定义尚未分配内存会导致编译错误!
int main()
{
//使用静态成员函数
test::func2();
//使用普通成员函数
test a; //实例化对象
a.func1(); //执行对象的函数
return 0;
}
void test::func1()
{
//使用静态成员变量state(每个对象)
state = 105;//改变静态成员函数
cout << "state:" << state << endl;
}
void test::func2()
{
state = 15;//改变静态成员函数
cout << "state:" << state << endl;
}
参考:
https://www.cnblogs.com/qintangtao/p/3285937.html
https://www.cnblogs.com/jhmu0613/p/7131997.html