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

在C++中有静态成员变量和静态成员函数,要注意,在C++类和对象的概念中,先有类,才有对象。因为static型的成员函数和成员变量是在类产生的时候分配的内存,产生于对象之前,静态成员函数和成员变量属于类,不属于对象,所以不能在static型函数中调用普通的成员变量和成同函数。同时,在static型函数后面也不能加const,这是C++的规则,const修饰符用于表示函数不能修改成员变量的值,该函数必须是含有this指针的类成员函数,函数调用方式为thiscall,而类中的static函数本质上是全局函数,调用规约是__cdecl或__stdcall,不能用const来修饰它。一个静态成员函数访问的值是其参数、静态数据成员和全局变量,而这些数据都不是对象状态的一部分。而对成员函数中使用关键字const是表明:函数不会修改该函数访问的目标对象的数据成员。既然一个静态成员函数根本不访问非静态数据成员,那么就没有必要使用const了。

下面用代码演示:
#ifndef CFILECOUNT_H
#define CFILECOUNT_H

#include <string>

class CFileCount
{
public:
    CFileCount(std::string fileName);
    ~CFileCount();
    void addFile(std::string fileName);
    static int getFileCount();//这就是静态成员函数

private:
    std::string m_strFileName;
    static int m_sCount;//静态成员变量
    int m_nNormal;//普通成员变量
};

#endif // CFILECOUNT_H


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

#include "CFileCount.h"

int CFileCount::m_sCount = 0;//静态成员初始化,必须用类名::静态成员变量的形式

CFileCount::CFileCount(std::string fileName)
{
    m_strFileName = fileName;
    m_sCount = 1;
    m_nNormal = 0;//普通成员变量在函数内初始化
}


CFileCount::~CFileCount()
{

}
void CFileCount::addFile(std::string fileName)
{
    m_strFileName = fileName;
    m_sCount += 1;
}

int CFileCount::getFileCount()
{
    //return m_nNormal;//静态成员函数使用非静态成员变量报错error: invalid use of member 'm_nNormal' in static member function
    return m_sCount;
}

最后在主函数中实现

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

using namespace std;

int main()
{
    //static函数和变量是在类编译时候就产生,不依赖于对象产生,所以不需要实例化对象就可以
    cout << "file count=====" << CFileCount::getFileCount() << endl;
    CFileCount *pFileCount = new CFileCount("a.png");//堆上分配内存
    int nCount = pFileCount->getFileCount();
    cout << "nCount=====" << nCount << endl;



    cout << "Hello World!" << endl;
    return 0;
}

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

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值