4. c++ 静态 对象

时间:2023-03-09 23:07:52
4. c++  静态 对象

参考自文章:http://blog.****.net/wpf_ml/article/details/7763534

1. 静态存储

变量定义在函数外或是用static 关键字修饰的变量存放在静态存储区(独立于堆和栈),放在静态存储区的数据在整个程序运行期间持续有效。既然在程序的整个生命周期都存在,这样的好处就是非常容易进行内存管理。

1.1 静态变量可以依据linkage分为以下三类:

(1)  external linkage (2)internal linkage  (3)no linkage

下面例子就是静态变量的不同作用域的示例.

int a= ;
static int b = ;
int main() {}
void f() {
static int c = ;
int d = ;
}

变量d是本地作用域,不能在函数f()以外使用。

变量c是静态的,即使f()函数没有被执行也会存在内存中。c是静态的,可以声明其一次并只能声明一次。(只能在一个文件中定义全局变量。也就是说,只有一个文件能提前声明,其它的文件必需通过extern关键字提供相关声明的引用)

a和b两个变量能从声明位置,到整个文件结束都能被访问到。但a能在其它文件中使用因为其默认为 external linkage。

特殊的例子:const 全局变量

const int a = ;
int main() { ....

一个全局变量默认是external linkage,一个const的全局变量默认是internal linkage

如果我们想使constant变量有external linkage,我们可以用extern关键字声明来代替默认的inernal linkage:

Extern const  int a = 20;

1.2 初始化

(1)为初始化的变量设置为0 (2) 初始化静态变量只能是固定表达式 ????

int x;               // x set to 0
int y = ; // 50 is literal constant
int z = sizeof(int); // sizeof ok
int zz = * x; // not allowed, x is not constant ? VS2010可以通过

2.  静态类成员

静态成员是作为这个类的成员而不是这个类的每一个实例存在。所以关键字this不能在静态成员中使用。

静态函数只能使用静态的数据成员。

整个类中静态成员只有一个实例,通常在实现源文件中被初始化。因为声明只是告诉编译器多少内存被申请,而不进行申请操作.我们只有在建立对象时才进行内存的申请及初始化。

但是在类的声明里面可以初始化const或 enumeration类型的静态成员:

#include <iostream>
class Car
{
enumColor {silver = , maroon, red };
intyear;
intmileage = ; //error: not-static data members
// only static const integral data members
// can be initialized within a class
static int vin = ; // error:non-constant data member
// only static const integral data members
// can be initialized within a class
static const string model = "Sonata"; // error: not-integral type VS2010实测,编译会报错,提示 only static const integral data members can be initialized within a class // can not have in-class initializer
         static const int engine = ;           //allowed: static const integral type
};
int Car::year = ; // error: non-static data members
// cannot be defined out-of-class
int main()
{
return0;
}

3. 静态成员函数

(1) 一个静态成员函数只能访问静态数据,静态函数及类外的数据和函数。所以我们必需注意不要向非静态成员一样使用静态成员函数,非静态函数能访问所有的静态数据成员。

(2)一个非静态函数只能在类对象初化时才能被调用。而静态数据成员可以在类没有初始化时就可以被调用。

(3)  一个非静态函数可以被声明为virtual但静态数据成员不能声明为virtual.