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;
    }
  • 相关阅读:
    HDU1285-确定比赛名次(拓扑排序)
    ftp sftp
    Python with 用法
    odoo 非root用户运行不成功
    linux 删除软连接
    vscode wsl php
    WSL 修改默认登录用户为root
    WSL ssh服务自启动
    odoo 获取model的所有字段
    odoo 在"动作"("Action")菜单中添加子菜单, 点击子菜单弹窗自定义form
  • 原文地址:https://www.cnblogs.com/simayuhe/p/6064877.html
Copyright © 2011-2022 走看看