C++静态数据成员的引用

静态数据成员可以初始化,但只能在类体外进行初始化
如:
Int Box::height=10;
不能够使用参数初始化列表对静态数据成员进行初始化。

#include <iostream>

using namespace std;

class Box{
public:
    Box(int,int);
    int volume();
    static int height;
    int width;
    int length;


};
Box::Box(int w , int len) {   //静态数据成员height必须在类外进行初始化

    width=w;
    length=len;

}
int Box::volume() {
    return(height*width*length);
}
int Box::height=10;     //对对象的静态数据成员进行初始化,并且对象的静态数据成员初始化,必须在类的外部进行初始化

int main()
{
    Box a(15,20),b(20,30);
    cout<<a.height<<endl;    //通过对象a引用静态数据成员
    cout<<b.height<<endl;     //通过对象b引用静态数据成员
    cout<<Box::height<<endl;     //通过类名引用静态数据成员,这个时候,要加上数据的作用域,即同一类型的作用域
    cout<<a.volume()<<endl;   //调用volume函数,计算体积,输出结果。

    return 0;
}

静态成员函数

**#include <iostream>

using namespace std;
class Student{
public:
    Student(int n,int a,int 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;
}

**

/home/andrew/文档/Clion/untitled5/cmake-build-debug/untitled5
please input the number of students:3
The average score of3student is82

Process finished with exit code 0

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

Achou.Wang

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值