//static 也就是类中所有共享成员 //static的优点: // 1、静态成员的名字是在类的作用域中,两个类有同样名称的静态成员,互不影响; //2、可以实时封装,类的成员可以是私有的 //3、 //定义static成员,使用类的static成员 //static成员函数不可以使用this指针,静态成员函数不属于任何一个对象 // #include <iostream> #include <string> //全局变量 double interestRate; //所有的类都可以使用此利率,如果只想让Account类使用,则让 class Dog{ }; class Account{ public: Account(std::string name, double money): owner(name), amount(money){} //构造函数 double getAmount() const{ return this-> amount; } void applyint(){ amount += amount * interestRate; } void deposit(double money){ this->amount += money; } double rate(){ return interestRate; } static void rate(double newRate){ //更改利率 interestRate = newRate; } private: std::string owner; double amount; static double interestRate ; //只有一个 static const int period = 30; //静态常量整型可以直接初始化,这是个例外 }; double Account ::interestRate = 0.015; using namespace std; int main(){ interestRate = 0.015; //Account ::interestRate = 0.015;//此时intereRate是私有成员,不可以初始化 Account::rate(0.026); //静态函数可以通过类作用域标识符调用函数,并更改利率 Account a("张三", 1000); Account b("李四", 2000); a.deposit(500); b.deposit(600); cout << a.getAmount() << endl; cout << b.getAmount() << endl; cout << a.rate() << endl; a.rate(0.018); //通过a更改利率 cout << b.rate() << endl; //通过b查看利率 Account::rate(0.02); //静态成员 a.applyint(); b.applyint(); cout << a.getAmount() << endl; cout << b.getAmount() << endl; return 0; }
C++面向对象程序设计——static 类成员
最新推荐文章于 2022-07-14 01:42:07 发布