关于静态变量
2016-04-29 19:26 迷你天才 阅读(182) 评论(0) 编辑 收藏 举报题目:
实验题1.商店销售某一商品,商店每天公布统一的折扣(discount),同时允许销售人员在销售时灵活掌握售价(price),在此基础上,对一次购10件以上者,还可以享受9.8折优待。现已知当天3个销货员的销售情况为:
销货员号(num) 销货件数(quantity) 销货单价(price)
101 5 23.5
102 12 24.56
103 100 21.5
编写程序,计算出当日此商品的总销售款sum,以及每件商品的平均售价,要求用静态数据成员和静态成员函数。
提示:将折扣discount,总销售款sum和商品销售总件数n声明为静态数据成员,在定义静态成员函数Average(求平均价)和display(输出结果)
#include<iostream> #include<string> using namespace std; class Shop { private: int n;//个数 static float sum;//总和 static float dicount;//折扣 float price;//单价 public: static int Average(); static int display(); Shop(int n, float price) :n(n), price(price) {}; int totlo(); }; float Shop::sum = 0; int Shop::Average() { return sum / 3; } int Shop::display() { cout << sum << endl; cout << Average() << endl; return 0; } int Shop::totlo() { if (n > 10) { sum = 0.98*n*price; } else { sum = n*price; } return 0; } int main() { Shop shop[3] = { Shop(5,23.5),Shop(12,24.56),Shop(100,21.5) }; for (int i = 0; i < 3; i++) { shop[i].totlo(); shop[i].Average(); shop[i].display(); } return 0; }
关于以上代码 (除了求平均值外都是对的)
静态变量 可以直接调用 但是必须在类外进行初始化
Shop(int n, float price) :n(n), price(price) {};
以上是构造函数语句 需要这样初始化(初始化之前需要定义变量 且变量不能是静态的) 如果在函数体内定义 只能定义上第一个数字