关于变局变量的问题,有知道的,请留言,多谢了,小弟不知道,两个程序毛病错在哪里,如果想在示例二中得到想要的(6)结果,应该怎样做?示例一:
.h与.cpp没有分开,得到正确的结果
示例二:
.h与.cpp分开,得到错误的结果例一代码:
//t_i.h
#ifndef t_i_h
#define t_i_h
static int i;
#endif//t_i_add.h
#include "t_i.h"
#include "stdio.h"
class t_i_add
{
public:
void print_i_add()
{
i++;
printf("t_i_add.h  i=%d\n", i);
}
};// test.cpp
#include "t_i.h"
#include "t_i_add.h"
int main(int argc, char* argv[])
{
i = 5;
t_i_add test_i;
test_i.print_i_add();      //此处打印出 "6"
return 0;
}
例二代码:
//t_i.h
#ifndef t_i_h
#define t_i_h
static int i;
#endif//t_i_add.h
#include "t_i.h"
#include "stdio.h"
class t_i_add
{
public:
void print_i_add();
};//t_i_add.cpp
#include "t_i_add.h"
void t_i_add::print_i_add()
{
i++;
printf("t_i_add.h  i=%d\n", i);
}// test.cpp
#include "t_i.h"
#include "t_i_add.h"
int main(int argc, char* argv[])
{
i = 5;
t_i_add test_i;
test_i.print_i_add();      //此处打印出 "1"
return 0;
}

解决方案 »

  1.   

    不可以的,程序会出错,我的MSN: [email protected],那里更多便
      

  2.   

    //t_i.h
    static int i=5;要是这样做,和最初的i=0有什么分别呢?要的解决问题的方面,不是免强地打印出一个数值
      

  3.   

    //t_i.h
    #ifndef t_i_h
    #define t_i_h
    extern int i;
    #endif
    // test.cpp
    #include "t_i.h"
    #include "t_i_add.h"int i;int main(int argc, char* argv[])
    {
    i = 5;
    t_i_add test_i;
    test_i.print_i_add();      //此处打印出 "6"
    return 0;
    }
      

  4.   

    多谢 回复人: danieltang(蓝色激情)
    按你的做法,一切OK