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;
    }
  • 相关阅读:
    023-Spring Boot 服务的注册和发现
    022-Spring Boot 构建微服务实战
    021-Spring Boot 测试,Junit方式使用,mock方式,Controller测试
    020-Spring Boot 监控和度量
    003-Spring 中的StreamUtils
    004-微信证书问题
    019-Spring Boot 日志
    018-Spring Boot Starter开发
    017-Spring Boot AOP
    016-Spring Boot JDBC
  • 原文地址:https://www.cnblogs.com/simayuhe/p/6064877.html
Copyright © 2011-2022 走看看