C++之static

 1 #include <iostream>
 2 
 3 using namespace std;
 4 //static类成员
 5 
 6 class Account
 7 {
 8 public:
 9     Account(string name,double money):
10         owner(name),amount(money){}
11     double getAmount() const
12     {
13         return this->amount;
14     }
15     void sepoist(double money)
16     {
17         this->amount+=money;
18     }
19     //静态函数操作静态的数据成员
20     //静态的成员函数中不能使用this指针
21     static double rate()
22     {
23         return interestRate;
24     }
25     static void rate(double newinterestRate)
26     {
27         interestRate=newinterestRate;
28     }
29 private:
30     string owner;
31     double amount;
32     //将利率设置成为静态的数据成员,即利率只有一个
33     //所有的对象都使用一个利率
34     static double interestRate;
35 };
36 //进行初始化
37 double Account::interestRate=0.015;
38 
39 int main()
40 {
41     //静态的函数可以用类名直接调用
42     Account::rate(0.026);
43     Account a("张三",1000);
44     Account b("李四",2000);
45     a.sepoist(500);
46     b.sepoist(600);
47     cout<<a.getAmount()<<endl;
48     cout<<b.getAmount()<<endl;
49     cout<<a.rate()<<endl;
50     a.rate(0.018);
51     cout<<b.rate()<<endl;
52 
53     return 0;
54 }

猜你喜欢

转载自www.cnblogs.com/yh2924/p/12642492.html