C++(static使用注意,和非static区别) C++(static使用注意,和非static区别)

C++(static使用注意,和非static区别)

  • C++类中的static
    在C++中有静态成员变量和静态成员函数,要注意,在C++类和对象的概念中,先有类,才有对象。因为static型的成员函数和成员变量是在类产生的时候分配的内存,产生于对象之前,故不能再static型函数中调用普通的成员变量和成员函数。而且在static型函数后面不能加const(原因注释里有)
    下面通过代码说明:
    #ifndef Tank_h_
    #define Tank_h_
    class Tank
    {
    public:
        Tank(char code);
        ~Tank();
        void fire();
        static int getCount();//这就是静态成员函数
    
        //static int getCount() const;//这种在static后面加const的行为是非法的,因为加const的本质是在给this指针加一个const,但static型成员函数的
    
            //里没有this指针,因为其是依托于类的,不是依托于对象的,this本质就是对象,这里不需要对象,所以没有this指针
    
    private:
        char m_cCode;//坦克编号
        static int s_iCount;//用静态变量来计数
    
    };
    #endif
    

在实现这些函数和变量初始化的时候,也要注意,具体见代码

#include "Tank.h"
#include <iostream>
using namespace std;


int Tank::s_iCount = 0;//这里是对类里面静态成员变量的初始化。
                                //要特别注意,static型变量不能再构造函数中初始化,而且不用加static关键字了

Tank::Tank(char code)
{
    m_cCode = code;
    s_iCount++;
    cout << "tank" << endl;
}

Tank::~Tank()
{
    s_iCount--;
    cout << "~Tank" << endl;
}

void Tank::fire()
{
    cout << "Tank--fire" << endl;
}


//这里就是static型函数的初始化
//注意这里不加static关键字
//而且注意,在static函数中不能调用普通的成员变量和普通的成员函数。
int Tank::getCount()
{
    return s_iCount;
}

最后在主函数中实现

#include <iostream>
#include "Tank.h"

using namespace std;

int main()
{
    cout<<Tank::getCount()<<endl;//这里注意,static函数和变量是在类编译时候就产生,不是依托于对象产生的。所以不需要实例化对象就可以

    Tank* p = new Tank('A');//堆上分配内存
    cout << p->getCount() << endl;
    system("pause");
    return 0;
}

这就是C++类中使用static的注意事项。

猜你喜欢

转载自blog.csdn.net/qq_32621445/article/details/84497753