首页 > 其他 > 详细

第26课 类的静态成员函数

时间:2016-04-16 00:42:45      阅读:162      评论:0      收藏:0      [点我收藏+]

1. 静态成员函数

(1)静态成员函数是类中特殊的成员函数,属于整个类所有

(2)可以通过类名直接访问公有静态成员函数

(3)可以通过对象名访问公有静态成员函数

(4)静态成员函数的定义:直接通过static关键字修饰成员函数

【编程实验】静态成员函数示例

#include <stdio.h>

class Test
{
private:
    int i;
    static int s_j;
public:

    int getI();
    static void StaticFunc(const char* s);
    static void StaticSetI(Test&d, int v);
    static int StaticGetJ();
};

int Test::getI()
{
    return i;
}

void Test::StaticFunc(const char* s)
{
    printf("StaticFunc: %s\n", s);
}

void Test::StaticSetI(Test&d, int v)
{
    d.i = v;
    //i = v;//静态成员函数不能访问非静态成员变量
    s_j = v;//合法,访问静态成员变量
}

int Test::StaticGetJ()
{
    return s_j;
}

int Test::s_j = 0;

int main()
{
    Test::StaticFunc("main Begin...");//通过类名调用静态成员函数

    Test t;

    Test::StaticSetI(t, 10); 

    printf("t.i = %d\n", t.getI());
    printf("s_j = %d\n", t.StaticGetJ());//通过对象名调用静态成员函数

    Test::StaticFunc("main End...");//通过类名调用静态成员函数    
    return 0;
}

2. 静态成员函数 VS 普通成员函数

 

静态成员函数

普通成员函数

所有对象共享

Yes

Yes

隐含this指针

No

Yes

访问普通成员变量/函数

No

Yes

访问静态成员变量/函数

Yes

Yes

通过类名直接调用

Yes

No

通过对象可直接调用

Yes

Yes

【编程实验】解决方案

#include <stdio.h>

class Test
{
private:
    static int cCount;
public:
    Test(){cCount++;}

    ~Test(){--cCount;}

     static int getCount(){return cCount;}
};

int Test::cCount = 0;


int main()
{
    printf("count = %d\n", Test::getCount());//0,通过类名调用函数

    Test t1;
    Test t2; 

    printf("count = %d\n", t1.getCount());//2, 通过对象名调用函数
    printf("count = %d\n", t2.getCount());//2, 通过对象名调用函数

    Test* pt = new Test();

    printf("count = %d\n", pt->getCount());//3

    delete pt;

    printf("count = %d\n", Test::getCount());//2,通过类名调用函数 
     
    return 0;
}

3. 小结

(1)静态成员函数是类中特殊的成员函数

(2)静态成员函数没有隐藏的this参数

(3)静态成员函数可以通过类名直接访问

(4)静态成员函数只能直接访问静态成员变量/函数

第26课 类的静态成员函数

原文:http://www.cnblogs.com/5iedu/p/5397298.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!