类中静态变量

不能在类声明中 初始化静态变量,这是因为声明描述了如何分配内存,但并未实际分配内存。

对于静态类成员,无论这个类的对象有多少个,静态成员都只有一个

对于静态类成员,可以在类声明之外使用单独的语句来进行初始化。

因为静态类成员是单独存在的,不属于对象的组成部分


例子

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;

在这里插入图片描述

  • 3
    点赞
  • 7
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值