码迷,mamicode.com
首页 > 其他好文 > 详细

第26课 类的静态成员函数

时间:2016-04-16 00:43:30      阅读:191      评论: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
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!