使用static成员的注意事项:
1、static成员 类内声明,类外定义。
2、static函数两种调用方式,(1)每个成员调用(2)类名调用 没用this指针
3、static不能调用成员函数(内联函数不会带来函数开销)
static 函数没有隐式参数。
static函数不能为const。
static函数不能调用普通成员,普通函数可以调用static成员。
函数定义在class内部,默认为内联函数
#include <iostream>
#include <string>
#include <vector>
using namespace std;
class Test
{
public:
Test()
{
count++;
}
~Test()
{
count--;
}
static void print()
{
cout << "当前对象个数: " << count << endl;
}
private:
static int count; //表示对象的个数
};
int Test::count = 0;
int main(int argc, const char *argv[])
{
Test::print();
Test t1;
<span style="white-space:pre"> </span>//t1.count编译错误无法外部调用
t1.print();
Test t2;
t1.print();
t2.print();
return 0;
}
</pre><pre name="code" class="cpp">//下面这个例子就可以知道 static成员函数,里面没有this隐藏参数
#include <iostream>
#include <string>
#include <vector>
#include <functional>
using namespace std;
class Foo
{
public:
void foo(int i) { cout << i << endl; }
static void bar(double d) { cout << d << endl; }
};
int main(int argc, const char *argv[])
{
//mem_fun void (*)(Foo *, int)
Foo f;
function<void(int)> pf1 = bind(&Foo::foo,
&f,
std::placeholders::_1);
pf1(456);
function<void (double)> pf2 = bind(&Foo::bar,
std::placeholders::_1);
pf2(456.9);
// function<void (int, Foo*)> pf3 = bind(&Foo::foo,
// std::placeholders::_2,
// std::placeholders::_1);
// pf3(567, &f);
return 0;
}
下面这段代码可以说明static变量的作用域和生命周期
#include <iostream>
#include <string>
#include <vector>
#include <functional>
using namespace std;
void test(int i, double d, const string &s)
{
static int c=0;
cout << "i = " << i << " d = " << d << " s = " << s << endl;
}
int main(int argc, const char *argv[])
{
c=1;
{
static int a=1;
}
a=0;
return 0;
}
编译提示 a,c没有被定义
ps:虽然不建议返回局部变量的指针,但是下面这种做法可以正确运行的
int* test(int i, double d, const string &s)
{
static int c=0;
int* p=&c;
//cout << "i = " << i << " d = " << d << " s = " << s << endl;
return p;
}
int main(int argc, const char *argv[])
{
int*p=test(1,2,"hello");
cout<<p<<endl;
// c=1;
// {
// static int a=1;
// }
// a=0;
return 0;
}