zoukankan      html  css  js  c++  java
  • 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;
    }
  • 相关阅读:
    生成器,生成器表达式。
    device busy
    memcached
    ps f
    Eviews9.0---软件安装
    免费提取百度文库 doc 文件
    Matlab---length函数
    Matlab 路径函数
    matlab中disp函数的简单用法
    MATLAB---dir函数
  • 原文地址:https://www.cnblogs.com/simayuhe/p/6064877.html
Copyright © 2011-2022 走看看