static在c++中

第一个例子,通过类名调用静态成员函数和非静态成员函数

 

class Point  

{  

public:   

    void init()  

    {    

    }  

    static void output()  

    {  

    }  

};  

void main()  

{  

    Point::init();  

    Point::output();  

}  

编译出错:error C2352: 'Point::init' : illegal call of non-static member function

 

结论1不能通过类名来调用类的非静态成员函数

 

 

第二个例子,通过类的对象调用静态成员函数和非静态成员函数

 

将上例的main()改为:

 

void main()  

{  

    Point pt;  

    pt.init();  

    pt.output();  

}  

编译通过。

 

结论2类的对象可以使用静态成员函数和非静态成员函数。

 

 

第三个例子,在类的静态成员函数中使用类的非静态成员

 

#include <stdio.h>  

class Point  

{  

public:  

Void point(){} 

    void init()  

    {    

    }  

    static void output()  

    {  

        printf("%d\n", m_x);  

    }  

private:  

    int m_x;  

};  

void main()  

{  

    Point pt;  

    pt.output();  

}  

编译出错:error C2597: illegal reference to data member 'Point::m_x' in a static member function

 

因为静态成员函数属于整个类,在类实例化对象之前就已经分配空间了,而类的非静态成员必须在类实例化对象后才有内存空间,所以这个调用就出错了,就好比没有声明一个变量却提前使用它一样。

 

结论3静态成员函数中不能引用非静态成员。

 

 

第四个例子,在类的非静态成员函数中使用类的静态成员

 

class Point  

{  

public:   

    void init()  

    {    

        output();  

    }  

    static void output()  

    {  

    }  

};  

void main()  

{  

    Point pt;  

    pt.output();  

}  

编译通过。

 

结论4类的非静态成员函数可以调用用静态成员函数,但反之不能。

 

 

第五个例子,使用类的静态成员变量

 

#include <stdio.h>  

class Point  

{  

public:   

    Point()  

    {    

        m_nPointCount++;  

    }  

    ~Point()  

    {  

        m_nPointCount--;  

    }  

    static void output()  

    {  

        printf("%d\n", m_nPointCount);  

    }  

private:  

    static int m_nPointCount;  

};  

void main()  

{  

    Point pt;  

    pt.output();  

}  

Ctrl+F7编译无错误,按F7生成EXE程序时报链接错误

 

error LNK2001: unresolved external symbol "private: static int Point::m_nPointCount" (?m_nPointCount@Point@@0HA)

 

这是因为类的静态成员变量在使用前必须先初始化。

 

main()函数前加上int Point::m_nPointCount = 0;

 

再编译链接无错误,运行程序将输出1

 

结论5:类的静态成员变量必须先初始化再使用。

 

 

 

 

 

结合上面的五个例子,对类的静态成员变量和成员函数作个总结:

 

一。静态成员函数中不能调用非静态成员。

 

二。非静态成员函数中可以调用静态成员。因为静态成员属于类本身,在类的对象产生之前就已经存在了,所以在非静态成员函数中是可以调用静态成员的。

 

三。静态成员变量使用前必须先初始化(int MyClass::m_nNumber = 0;),否则会在linker时出错。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值