学习资料网址:
C++类中的static:C++类中的static - h_hg - 博客园
1.static声明变量的知识点
<1>要在类外初始化
<2>所有对象共用的变量
<3>不需要声明对象也可以调用
#include <iostream>
using namespace std;
class test
{
private:
public:
static int i;
};
//此句包含了声明和赋值,初始化不受private和protected访问限制,
//但是若是priivate,下面main函数就无法访问
//初始化在类外,注意也有int修饰
int test::i; //没有这句编译会失败error: undefined reference to `test::i'
int main()
{
//没有声明对象也可以调用
test::i=50;
cout << test::i << endl;
return 0;
}
2.static成员函数的知识点
<1>不能访问非static的类成员,只能访问 static修饰的类成员
<2>不需要定义对象,直接调用test::f();
class test
{
public:
static int i;//此处只是声明变量
static void f();//声明
};
int test::i;//此处是定义,少了此处会链接错误
void test::f()//定义
{
i = 1000;
cout << i << endl;
}
int main()
{
//test a;
test::f();
return 0;
}
<3>test::f()调用同类中其它函数,需要定义object
<4>非static的类函数print可以直接调用static 的i
实验如下
/*
*实验static
*
*/
#include <signal.h>
#include <string>
#include <sstream>
#include <iostream>
#include <memory>
using namespace std;
#define INSTANCE_IMP(class_name, ...) \
class_name &class_name::Instance() { \
static std::shared_ptr<class_name> s_instance(new class_name(__VA_ARGS__)); \
static class_name &s_insteanc_ref = *s_instance; \
return s_insteanc_ref; \
}
class test
{
public:
void add(int x,int y){
cout<<"x+y="<<(x+y)<<endl;
}
//验证类中调用static 变量,是可以定义的
void print(){
i = 10;
cout<<"i="<<i<<endl;
}
public:
static test &Instance();
static int i;//此处只是声明变量
static void f();//声明
};
int test::i;//此处是定义,少了此处会链接错误
INSTANCE_IMP(test);
void test::f()//定义
{
i = 1000;
cout <<"i="<< i << endl;
test::Instance().add(1,2);//定义object才能调用
/*
error: cannot call member function ‘void test::add(int, int)’ without object
add(0,1);
*/
//add(0,1);//没有定义object会出错
}
int main()
{
//test a;
test::f();
test::Instance().print();
return 0;
}
其它知识点实验
在函数中定义名字一样的变量名,会是同一个地址不? 实验如下
不是同一个地址,是两个地址
int test_kk1()
{
static int kk = 10;
cout<<"1 kk="<<&kk<<"="<<kk<<endl;
return 0;
}
int test_kk2()
{
static int kk = 5;
cout<<"2 kk="<<&kk<<"="<<kk<<endl;
return 0;
}
在回调函数上的使用
class test
{
public:
static bool CallbackFunc(void* pData, int change);
bool CallbackFunc1(int change);
};
bool test::CallbackFunc(void* pData, int change)
{
if (pData)
{
test* pTest = (test*)pData;
pTest ->CallbackFunc1(change);
}
return true;
}
bool test::CallbackFunc1(int change)
{
std::cout<<"change="<<change<<std::endl;
}