c++学习笔记之static成员

使用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;
}




  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值