C++ 之类的静态成员

一.静态数据成员:

1.如果想在同类的多个对象之间实现数据共享,也不要用全局变量,可以用静态的数据成员;

2.静态数据成员属于类,而不属于对象,静态数据成员是在所有对象之外单独开辟空间,所有对象都共享这些数据成员;

3.静态数据成员是在程序编译时被分配空间的,到程序结束时才释放空间;

4.静态数据成员可以初始化,但只能在类体外进行初始化;

如: int Box::height = 10;   // 表示对Box类的数据成员初始化

5.静态数据成员既可以通过对象名引用,也可以通过类名引用;

6.静态数据成员被定义为私有后,则不能在类外直接引用,必须通过公用的成员函数引用;

#include <stdio.h>

class time
{
public:
    void printf_test(void);
private:
    static int test;
};

void time::printf_test(void)
{
    printf("test = %d\n",test);
}

int time::test = 10;

int main()
{
    time t1;
    t1.printf_test();
    return 0;
}

二.静态成员函数

1.静态成员函数属于类,不属于对象,没有this指针,不能直接访问本类中的非静态成员;

2.公用静态成员函数可以在类外直接调用,通用通过对象或类名直接调用;类名需要加域运算符"::";

#include <iostream>

using namespace std;
class Student
{
public:
    Student(int n,int a,float s):num(n),age(a),score(s){};
    void total();
    static float average();
private:
    int num;
    int age;
    float score;
    static float sum;
    static int count;
};

void Student::total()
{
    sum+=score;
    count++;
}

float Student::average()
{
    return(sum/count);
}

float Student::sum = 0;
int Student::count = 0;

int main()
{
     Student stud[3]={
         Student(1001,18,70),
         Student(1002,19,78),
         Student(1005,20,98)
        };
    int n;
    cout<<"please input the number of students";
    cin>>n;
    for(int i=0; i<n; i++)
    stud[i].total();
    cout<<"the average score of"<<n<<"student is"<<Student::average()<<endl;
    return 0;
}
    

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值