【C++】5.1静态数据成员的实现,建立一个学生成绩的线性表,要求输出每个学生的信息和总人数。

定义格式:static 类型名 成员名 ;
初始化格式:类型 类名::成员名=初始值;
一.

#include<iostream>
using namespace std;
#include<iomanip>
#include<string.h> 
class student{
	private:
		char *name;
		int num;
		float score;
		static int total;
		public:
			student(char *na,int nu,float sco);
			void print();
};
int student::total=0;
int main()
{
	student s1("小王",1,85);
	s1.print();
	student s2("李四",2,90);
	s2.print();
	student s3("王五",3,89);
	s3.print();
	return 0;
}
student::student(char *na,int nu,float sco)
{
	name=new char[strlen(na)+1];
	strcpy(name,na);
	num=nu;
	score=sco;
	total++;
}
void student::print()
{
	cout<<"第"<<total<<"个学生:"<<endl<<name<<setw(4)<<num<<setw(4)<<score<<endl; 
	cout<<"总人数是:"<<total<<endl;
}

运行结果:
第1个学生:
小王 1 85
总人数是:1
第2个学生:
李四 2 90
总人数是:2
第3个学生:
王五 3 89
总人数是:3


二.静态数据成员的应用。

#include<iostream>
using namespace std;
class A{
	private:
		static int a;
		int b;
		public:
			A(int i,int j);
			void print();
	 
};
int A::a;
int main()
{
	A a1(1,1);
	a1.print();
	A a2(2,2);
	a2.print();
	a1.print();
	return 0;
}
A::A(int i,int j)
{
	a=i;
	b=j;
}
void A::print()
{
	cout<<"this static a is:"<<a<<endl;
	cout<<"this not static is:"<<b<<endl;
}

运行结果:
this static a is:1
this not static is:1
this static a is:2
this not static is:2
this static a is:2
this not static is:1


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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值