C++数据共享与保护static超市大米篇 待我称王封你为后i 2022-11-21 04:11 170阅读 0赞 ## static的用法 ## c++类的各个对象之间如果需要同一个相同的数据时候就可以用static变量来共享数据,用static函数来对static变量进行修改。列如,一个班的学生的数据中班主任就是共享的,那么就可以用static来进行存储和修改。。。。。。。 eg.超市经销大米,成袋购入,成袋售出。每袋大米的质量有2.5公斤的、有5公斤、有10公斤的等,超市记录所有大米的总质量。 构造rice类,包含重量,产地,以及重质量等,其中总质量应该属于所有对象共同的,而且每当构造一个对象或者析构一个对象时,总重量都应该发生变化。代码如下 #include<iostream> #include<string> using namespace std; class Rice{ private: double Weight; string Place; static double TotalWeight;//静态变量记录总的重量 public: Rice(double weight=0,string place = "xxx");//rice类构造函数 double getWeight()const{ //#1 const表示不会对类做任何修改 return Weight; } string getPlace()const{ return Place; } Rice(const Rice&);//拷贝构造函数 ~Rice();//析构函数 static double GetTotal();//静态函数是返回总重量 }; double Rice::TotalWeight=0;//初始化总重量 Rice::Rice(double weight,string place){ this->Weight=weight; this->Place=place; TotalWeight+=this->Weight; } Rice::Rice(const Rice& p){ Weight=p.getWeight(); Place=p.getPlace(); TotalWeight+=this->Weight; } Rice::~Rice(){ TotalWeight-=this->Weight;//析构一个对象时,要减去它的重量 } double Rice::GetTotal(){ return TotalWeight; } int main(){ Rice r1(2.5,"abc"); Rice *r2=new Rice(5); Rice r3(*r2); cout<<Rice::GetTotal()<<endl; delete r2; cout<<Rice::GetTotal()<<endl; return 0; } \#1处函数后用const是表明这个函数不会对对象做任何修改,在传参时如果用const引用就不会报错
还没有评论,来说两句吧...