怎样使用类和对象——静态成员

静态数据成员

  • 用立方体类box定义两个对象,引用不同对象中的静态数据成员。
#include<iostream>
using namespace std;
class box
{public:
box(int,int);
int v();
static int height;  //把height定义为公用的数据成员函数
int width;
int length;
};
box::box(int w,int l)
{
  width = w;
  length = l;
}
box::v()
{return(height*width*length);}
int box::height = 10; //对静态成员height初始化
int main()
{


  • 将折扣discount 总销售款sum 以及商品销售总件数n声明为静态数据成员,在定义静态成员函数average和display(输出结果)
#include <iostream>
using namespace std;
class product
{
  public:
  product(int n,int q, float p):num(n),quantity(q),price(p){};
  static float average();
  static void display();
  void total();
  private:
  int num;
  int quantity;
  float price;
  static float discount;
  static float sum;
  static int n;
  };
  void product::total()
  {
    float rate = 1.0;
    if(quantity > 10)
    rate = rate *0.98;
    sum = sum + quantity*price*rate *(1-discount);
  n = n +quantity;
  }
  float product::average()
 {
   return(sum/n);}
 void product :: display()
 {
   cout << sum << endl;
   cout << average() << endl;
   }
   float product::discount = 0.05;
   float product :: sum = 0;
   int product :: n = 0;
   int main()
   {
   product prod[3] = { product(101, 5, 23.5),
   product(102,12,24.56),
   product(103,100,21.5)};
   for(int i = 0;i < 3; i++)
   prod[i].total();
   product::display();
   return 0;
   }
      

程序运行结果

1256.66
10.7407

Process returned 0 (0x0)   execution time : 0.033 s
Press any key to continue.
  • 统计学生平均成绩,用静态成员函数
#include<iostream>
using namespace std;
class student
{public:
student(int n,float s):num(n),score(s){}
void total();
static float average();
private:
int num;
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 stud1[3] = {student(2021621,89.5),
 student(2021622,98.6),
 student(2021623,98.5)};
 int n;
 cout << "please input the number of students: " << endl;
 cin >> n;
 for(int i = 0; i< n; i++)
  
 stud1[i].total();
 cout  << "the average score of "<<  n << "student is " << student::average() << endl;  //调用静态成员函数
 return 0;
 }

程序运行结果

please input the number of students:
3
the average score of3student is95.5333

Process returned 0 (0x0)   execution time : 4.059 s
Press any key to continue.
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值