类与对象之静态成员


定义

​ 静态成员就是在成员变量和成员函数前加关键词static。

分类

静态成员变量

  • 所以对象共享同一份数据
  • 在编译阶段分配内存
  • 类内声明,类外初始化

静态成员函数

  • 所有对象共享同一函数
  • 静态成员函数只能访问静态成员变量

简单实例

#include<iostream>
#include<string>
using namespace std;
class Person
{
public:
Person();
~Person();
static int m_A;
static void func()
{
m_A = 2000;
cout << "static void 调用" << endl;
}
private:

};
int Person::m_A = 10;
Person::Person()
{
}

Person::~Person()
{
}

void test01()
{
//通过对象进行访问
Person P;
//100
cout << "年龄:" << P.m_A << endl;
Person p2;
p2.m_A = 20;
//200
cout << "年龄:" << P.m_A << endl;
}

void test02()
{
//通过类名进行访问
cout << "年龄:" << Person::m_A << endl;
}
年龄:10
年龄:20
年龄:20
void test03()
{
//通过类名进行访问
Person::func();
cout << "年龄:" << Person::m_A << endl;
}
void test04()
{
//通过对象进行访问
Person P;
P.func();
cout << "年龄:" << P.m_A << endl;
}
static void 调用
年龄:2000
static void 调用
年龄:2000
int main()
{
test01();
test02();
test03();
test04();
system("pause");
return 0;
}

书本实例

#include<iostream>
#include<string>
using namespace std;
class Croster
{
string name;
int Math;
/*int English;*/
static int Sum;
public:
Croster(string na = "undef", int m = 100/*, int e = 100*/);
/*void Display();*/
static int Count;
static void Display();
};
#include "l4_03.h"
int Croster::Count = 100;
int Croster::Sum;
Croster::Croster(string na, int m) :name(na), Math(m)
{
cout << "欢迎新同学" << endl;
Count--;
Sum += Math;
}
void Croster::Display()
{
//cout<<"name:"<<name<<endl;
//静态成员函数不允许访问非静态成员
cout << "Sum:" << Sum << endl;
if (Count == 100)
{
cout << "Average=0" << endl;
}
else
cout << "Average=" << Sum * 1.0 / (100 - Count) << endl;
}
#include "l4_03.h"
int main()
{
Croster::Display();
Croster list[3] = { Croster("赵衍",95),Croster("钱多多",90),Croster("孙立",92) };
list[1].Display();
Croster stu_A("李梅");
stu_A.Display();
return 0;
}
Sum:0
Average=0
欢迎新同学
欢迎新同学
欢迎新同学
Sum:277
Average=92.3333
欢迎新同学
Sum:377
Average=94.25

Author: T1g3r
Reprint policy: All articles in this blog are used except for special statements CC BY 4.0 reprint policy. If reproduced, please indicate source T1g3r !
评论
  TOC