C++ 静态对象及静态成员
13. 静态对象
13.1 Static in C++
- Two basic meanings:
- Static storage
- allocated once at a fixed address
- Visibility of a name
- internal linkage
- Static storage
- Don't use static except inside functions and classes
- 示例一:Global static hidden in file
// file1.cpp
int g_global;
static int s_local; // s_local 只能在本文件中使用,具有持久化存储
void func() {
...
}
// hidden() 只能在 file1.cpp 中访问
static void hidden() {
...
}
// file2.cpp
extern int g_global;
13.2 静态成员
-
Static member variables
- Global to all class member functions
- Initialized once, at file scope
- provide a place for this variable and init it in .cpp
- No 'static' in .cpp
-
示例一:
#include <iostream>
using namespace std;
class A {
public:
A() { i = 0; }
void print() { cout << i << endl; }
void set(int ii){ i=ii; }
private:
static int i;
};
int main()
{
A a, b;
a.set(10);
b.print();
return 0;
}
- 示例二:成员变量为 static,需要在 cpp 文件中定义
#include <iostream>
using namespace std;
class A {
public:
A() { i = 0; }
void print() { cout << i << endl; }
void set(int ii){ i=ii; }
private:
static int i;
};
// 如果成员变量为 static,需要提供下面的语句进行定义
int A::i;
int main()
{
A a, b;
a.set(10);
b.print();
return 0;
}
- 示例三:编译失败
- initializer list 只能对非静态成员进行初始化
#include <iostream>
using namespace std;
class A {
public:
A():i(0) { }
void print() { cout << i << endl; }
void set(int ii){ i=ii; }
private:
static int i;
};
// 如果成员变量为 static,需要提供下面的语句进行定义
int A::i;
int main()
{
A a, b;
a.set(10);
b.print();
return 0;
}
13.3 静态成员函数
- 示例:
#include <iostream>
using namespace std;
class A {
public:
A() { i = 0; }
void print() { cout << i << endl; }
void set(int ii){ i=ii; }
static void say(int ii) { cout << ii << i << endl; }
// 静态函数,不能使用非静态成员 k
// static void say2(int ii) { cout << ii << k << endl; }
private:
int k;
static int i;
};
// 如果成员变量为 static,需要提供下面的语句进行定义
int A::i = 20;
int main()
{
A a, b;
a.set(10);
b.print();
a.say(0);
A::say(0);
return 0;
}
参考链接: