static靜態變量在c++類中的應用實例


這個static 如果寫在類中,那么就可以得到一個局部的靜態變量,也就是說可以實現在類內保存某個特殊值不隨函數釋放而消失的作用。應用中由於賦初值的位置不對而報錯,錯誤提示為:“無法解析外部符號 。。。”,這里將更改之后的代碼放上來:

mytest_static.h

#pragma once
class mytest_static
{
public:
    mytest_static();
    ~mytest_static();    
    // 記錄該函數被調用的次數
    int countformytest();
private:
    static int count;//這個就是要討論的靜態變量
};

mytest_static.cpp

#include "stdafx.h"
#include "mytest_static.h"
mytest_static::mytest_static()
{
}
mytest_static::~mytest_static()
{
}
int mytest_static::count;//這個賦初值是必須的*********
// 記錄該函數被調用的次數
int mytest_static::countformytest()
{
    //count = 0;
    count++;
    return count;
}

調用它們的主函數

// test_for_static.cpp : 定義控制台應用程序的入口點。
//弄清楚如何在類內使用static變量
#include "stdafx.h"
#include "mytest_static.h"
#include <iostream>

int _tmain(int argc, _TCHAR* argv[])
{
    mytest_static t;
    for (int i = 0; i < 3; i++)
    {
        std::cout<<t.countformytest()<<std::endl;
    }
    return 0;
}

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM