对静态变量的更改超出范围? (C ++) [英] changes to static variable goes out of scope? (C++)

查看:123
本文介绍了对静态变量的更改超出范围? (C ++)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个头文件包含静态变量,如窗口宽度和高度。



我通过XML文件读取这些变量的新值,但这些更改



示例说明:

  //这些在一个单独的头文件
static int width = 0;
static int height = 0;

aClass :: Init()
{
width = readFromXMLFile(); // returning 800
height = readFromXMLFile(); // returned 600

//这里的宽度和高度是800/600
}

aClass :: Run()
{
...
}

Main
{
Init()
//这里,宽度和高度都是0/0再次
Run ()
}


解决方案

t在一个地方声明一个静态作为extern,你最终会得到每个编译单元的静态的多个副本(同名)。



正确的例子: / p>

test.h

  extern int mystatic; 

test.cpp

  int mystatic = 0; 

void myFunction()//或成员函数,其关心
{
mystatic = 42;
}

main.cpp

  #includetest.h

int main()
{
std :: cout<神秘 std :: endl; // prints 0
//
myFunction(); //或使用类并触发相同的

//
std :: cout<神秘 std :: endl; // prints 42
return 0;
}

HTH


I have a header file containing static variables, such as window width and height.

I read new values for these variables through a XML file, but these changes does not seem to be registered once the function it was changed in, goes out of scope.

Example to illustrate:

// These are in a separate header file  
static int width = 0;  
static int height = 0;  

aClass::Init()  
{  
    width = readFromXMLFile(); // returning 800  
    height = readFromXMLFile(); // returning 600  

    // Here width and height are 800/600
}

aClass::Run()  
{  
    ...  
}  

Main  
{  
    Init()  
    // Here, width and height are 0/0 again  
    Run()
}  

解决方案

If you don't declare a static as extern somewhere, what you'll end up with are actually multiple copies of statics (by the same name) per compilation unit.

Correct example:

test.h

extern int mystatic;

test.cpp

int mystatic = 0;

void myFunction() // or member funciton, who cares
{
    mystatic = 42;
}

main.cpp

#include "test.h"

int main()
{
     std::cout << mystatic << std::endl; // prints 0
     // 
     myFunction(); // or use classes and trigger the same

     // 
     std::cout << mystatic << std::endl; // prints 42
     return 0;
 }

HTH

这篇关于对静态变量的更改超出范围? (C ++)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆