static成员变量的使用

最近自己在研究C++中static成员变量的注意事项,只是自我研究,仅供参考:

例如:

file1.h

#ifndef FILE_1_H
#define FILE_1_H

void func1(void);
void func2(void);
static int func(void);
#endif // FILE_1_H

file1.cpp

#include "file1.h"
#include <iostream>
using namespace std;

static int a;
void func1(void)
{
    cout << "a = " << a << endl;
    cout << "call a:" << endl;
    cout << "a = " << a << endl;
    a++;
    return;
}
void func2(void)
{
    cout << "call func2:" << endl;
    cout << "a = " << a << endl;
    a++;
    return;
}

void func(void)
{
    cout << "call static func" << endl;
    return;
}

  编译错误如下:

C:\Users\EADEFJI\codeblocksProjects\1007\file1.cpp||In function `void func()':|
C:\Users\EADEFJI\codeblocksProjects\1007\file1.cpp|23|error: new declaration `void func()'|
C:\Users\EADEFJI\codeblocksProjects\1007\file1.h|6|error: ambiguates old declaration `int func()'|
C:\Users\EADEFJI\codeblocksProjects\1007\file1.cpp|23|warning: 'void func()' defined but not used|
||=== Build finished: 2 errors, 1 warnings (0 minutes, 0 seconds) ===|

所以,最好不要在头文件中定义(初始化)某个静态数据成员或静态成员函数,而应该在相应的.cpp文件中定义及使用

posted @ 2013-12-07 17:06  亲亲小强  阅读(448)  评论(0编辑  收藏  举报