不能在类声明中 初始化静态变量,这是因为声明描述了如何分配内存,但并未实际分配内存。
对于静态类成员,无论这个类的对象有多少个,静态成员都只有一个
对于静态类成员,可以在类声明之外使用单独的语句来进行初始化。
因为静态类成员是单独存在的,不属于对象的组成部分
例子
static int nAmount;
int STUDENT::nAmount = 10;
#ifndef __STUDENT_H__
#define __STUDENT_H__
#include <iostream>
class STUDENT
{
private:
static int nAmount;
int nID;
int nAge;
public:
STUDENT();
STUDENT(int ID, int Age);
~STUDENT();
void SetID(int ID);
void SetAge(int Age);
int GetID(void) const;
int GetAge(void) const ;
friend std::ostream & operator<<(std::ostream & os,
const STUDENT & stu);
};
#endif
#include "Student.h"
int STUDENT::nAmount = 10;
STUDENT::STUDENT()
{
nAmount++;
}
STUDENT::STUDENT(int ID, int Age)
{
nID = ID;
nAge = Age;
nAmount++;
}
STUDENT::~STUDENT()
{
nAmount--;
}
void STUDENT::SetID(int ID)
{
nID = ID;
}
void STUDENT::SetAge(int Age)
{
nAge = Age;
}
int STUDENT::GetID(void) const
{
return nID;
}
int STUDENT::GetAge(void) const
{
return nAge;
}
std::ostream & operator<<(std::ostream & os, const STUDENT & stu)
{
os << stu.nID <<" "<< stu.nAge;
return os;
}
初始化语句指出了类型 而且 使用了作用域解析运算符 但没有加关键字static
查看static变量的值
初始化为10
class STUDENT a;
std::cout<<a<<std::endl;
class STUDENT b;
class STUDENT c;
std::cout<<c<<std::endl;