对于class中的静态数据成员(static data members),我们要知道这些点:
- a single piece of storage for a static data member, regardless of how many objects of that class you create.
- the static data belongs to the class. Its name is scoped inside the class and all objects share that data member
- NOTE: The linker will report an error if a static data member is declared but not defined.
问题就出在:在class中,无法对static data member进行赋值。因为static data member不属于任何一个对象,所以更不能在构造函数中复制,不然每次创建一个实例对象,静态数据成员都会重新赋初值。我们必须要在class外对其进行定义,也就是赋初值。
如果我们声明(declare)了一个static data member,却没有对其进行定义(define),就会导致在编译时产生undefined reference to xxx的错误,这是linker在告诉我们找不到类静态数据成员的初始定义。

解决方法:
- The definition must occur outside the class (no inlining is allowed), and only one definition is allowed.
- It is common to put it in the implementation file for the class.
我们可以在全局的地方对静态成员变量进行初始化(定义)。在初始化静态成员变量时不需要加static前缀,但要加类名限定。
class Date
{
public:
Date(int d = 0, int m = 0, int y = 0); //构造函数
int get_day() const; // 返回day
int get_month() const; //返回month
int get_year() const; // 返回year
private:
int day, month, year;
static Date default_date; //重点!需要在全局初始化,否则会报错
};
Date::Date(int d, int m, int y)
{
day = d;
month = m;
year = y;
}
Date Date::default_date = Date(1, 1, 1901); //这里进行了赋值初始化
初始化时也可以不赋值。实例如下:
class Date
{
public:
Date(int d = 0, int m = 0, int y = 0);
static Date default_date; //此时default_date是一个public的静态成员变量
private:
int day, month, year;
};
Date::Date(int d, int m, int y)
{
day = d;
month = m;
year = y;
}
Date Date::default_date;//这里仅仅进行了定义,但没有赋初值
int main()
{
Date::default_date = Date(1, 1, 1901);//在主函数进行了赋值
}
Comments | NOTHING